강의

멘토링

커뮤니티

Inflearn Community Q&A

No author

This post's author information has been deleted.

[Renewal] TypeScript All-in-One: Part 1. Basic Grammar

readonly, indexed signatures, mapped types

인덱스드 시그너치와 함수속성

Written on

·

350

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;
}
typescript

Answer 1

0

zerocho님의 프로필 이미지
zerocho
Instructor

[key: string]: T를 선언해서 join도 타입이 T여야 하는 것입니다. 다음과 같은 식으로 하세요.

interface userType<T> { readonly [key: string]: T; }

type UserWithJoin<T> = userType<T> & { join(separator?: string): string; }

이렇게 할 경우 결국 join이 string타입으로 잡혀서 join에 함수를 지정하지 못하지 않나요?

이렇게 쓰는 경우는 없겠지만 이런 형태의 타입으론 객체를 Typescript로 생성할수 없다고 이해해도 될까요?

const h: UserWithJoin<number> = {
    test: 1,
    join:() => '2'
}

변수 h에 "Type '() => string' is not assignable to type 'number'." 오류가 발생합니다

zerocho님의 프로필 이미지
zerocho
Instructor

네.

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 객체로 만들어 야할 것 같습니다.

zerocho님의 프로필 이미지
zerocho
Instructor

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',
}

No author

This post's author information has been deleted.

Ask a question