본문 바로가기
IT/typescript

[typescript] Array가 Record type에 호환이 된다고?

by 내일은교양왕 2024. 3. 13.

결론

맞다. 뿐만아니라 function, Map, Date, Boolean, String, class도 된다.

 

Record Type

type Record<K extends string | number | symbol, T> = { [P in K]: T; }

 

이유

key의 형태가 index signature로 되어 있기 떄문이다.

[P in K] 가 array['0'] 를 받아줄 수 있기 때문이다.

const a = [1, 2, 3, 4, 5]

const b: Record<number, number> = a

console.log('a', a) // [1, 2, 3, 4, 5] 
console.log('b', b) // [1, 2, 3, 4, 5] 
console.log('isArray', Array.isArray(b)) // true

 

 

더 신기한 사실!!

string 자체도 Record에 호환이 된다. 

이유는 string interface에 index signature가 있기 때문이다.

const c = "whoa"
const arr: Record<number, any> = c; // OK

console.log('arr',arr, c[0])

 

 

https://stackoverflow.com/questions/71422178/typescript-record-accepts-array-why

 

typescript Record accepts array, why?

Can anyone explain why this compiles in typescript? I tried some googling and looking it up in the typescript documentation but didn't find the answer. type RecType = Record<string, any> cons...

stackoverflow.com