인프런 영문 브랜드 로고
인프런 영문 브랜드 로고

Inflearn Community Q&A

grandamines's profile image
grandamines

asked

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

enum, keyof, typeof

타입 추론 시 가장 넓은 범위로 추론이 되는 건가요?

Resolved

Written on

·

72

·

Edited

0

먼저 테스트 해 본 코드 올립니다.

const obj = { a: '123', b: 'hello', c: 'world' } as { a: string, b: `hel${string}`, readonly c: 'world' };

type AType = typeof obj;
const objA: AType = { a: '123', b: 'hello', c: 'world' }

type BType = keyof typeof obj;
const objBa: BType = 'a';
const objBb: BType = 'b';
const objBc: BType = 'c';

// CType이 string이 됩니다.
type CType = typeof obj[keyof typeof obj];

위 코드에서 CType에 마우스 커서를 올려보면 type CType = string 이라고 알려주는데 왜 그런지 몰라 여쭤봅니다.

저는 obj 객체 안의 속성들 값의 타입인 string | `hel${string}` | 'world' 로 추론될 줄 알았습니다.

이유가 `hel${string}` 타입과 'world' 타입보다 string 타입이 범위가 가장 넓기 때문에 변수를 CType으로 지정하면 string 과 차이가 없어서 그런 것일까요?

typescript

Answer 1

1

zerocho님의 프로필 이미지
zerocho
Instructor

string | `hel${string}` | 'world' 이 값이 결국 string이라서 그렇습니다.

string | 'abc' 은 string 입니다

grandamines's profile image
grandamines

asked

Ask a question