-
카테고리
-
세부 분야
프로그래밍 언어
-
해결 여부
미해결
인덱스드 시그너치와 함수속성
23.06.26 09:24 작성 조회수 239
0
interface userType<T> {
readonly [key: number]: T;
join(separator?: string): string;
}
위 코드처럼 인덱스드 타입의 키 타입을 Number로 하면 오류가 발생하지 않지만 아래와 같이 string으로 바꾸면 join 속성에서 "Property 'join' of type '(separator?: string | undefined) => string' is not assignable to 'string' index type 'T'.(2411)
View Problem (⌥F8)" 오류가 발생합니다.
join은 함수의 매개변수와 반환타입을 가지고 있는데 왜 이런 오류가 발생하는걸까요?
interface userType<T> {
readonly [key: string]: T;
join(separator?: string): string;
}
답변을 작성해보세요.
0
조현영
지식공유자2023.06.26
[key: string]: T를 선언해서 join도 타입이 T여야 하는 것입니다. 다음과 같은 식으로 하세요.
interface userType<T> { readonly [key: string]: T; }
type UserWithJoin<T> = userType<T> & { join(separator?: string): string; }
하정훈
2023.06.26
이렇게 할 경우 결국 join이 string타입으로 잡혀서 join에 함수를 지정하지 못하지 않나요?
이렇게 쓰는 경우는 없겠지만 이런 형태의 타입으론 객체를 Typescript로 생성할수 없다고 이해해도 될까요?
const h: UserWithJoin<number> = {
test: 1,
join:() => '2'
}
변수 h에 "Type '() => string' is not assignable to type 'number'." 오류가 발생합니다
조현영
지식공유자2023.06.26
네.
interface userType<T> { [key: string]: T; }
type UserWithJoin<T> = userType<T> & { join?(separator?: string): string; }
const h: UserWithJoin<number> = { test: 1 }
h.join = () => 'hi';
이런 식으로 하거나 인덱스 시그니처를 top level property가 아니라 nested 객체로 만들어 야할 것 같습니다.
조현영
지식공유자2023.06.26
interface userType<T> {
[key: string]: T | ((s?: string) => string);
}
type UserWithJoin<T> = userType<T> & {
join(separator?: string): string;
}
const h: UserWithJoin<number> = {
test: 1,
join: () => 'hi',
}
답변 1