TypeScript에서는 안되는 것이 있는데, TypeScript는 JavaScript와 다르게 객체의 프로퍼티를 읽을 때, string타입의 key 사용을 허용하지 않는다.
const a = "Hello"
// 컴파일러가 a라는 변수를 string이 아닌 조금 더 좁은 타입으로 선언한 것으로 추론한다.
// (Literal Narrowing) => 'Hello'라는 string만을 허용하는 타입 선언
let b = "Hello"
// let으로 선언되어 재할당될 수 있을 경우 어떤 문자열이든 넣을 수 있고
// 그 경우의 수는 무한대이므로 컴파일러가 이 변수를 string 타입으로 추론한다.
const c: string = "Hello"
// string 타입으로 선언했으므로 string 타입이다.
해결
const someObj:ObjectType = data;
const field = 'username';
// This gives an error
const temp = someObj[field];
// Solution 1: When the type of the object is known
const temp = someObj[field as keyof ObjectType]
// Solution 2: When the type of the object is not known
const temp = someObj[field as keyof typeof someObj]