1.未定義類型對象
const obj = {
a: 1,
b: 1,
c: 1,
}
type ObjKey = keyof typeof obj // type ObjKey = "a" | "b" | "c"
2.定義類型的對象
當(dāng)希望約定obj的類型時(shí),便無法推導(dǎo)出key
const obj: Record<string, number> = {
a: 1,
b: 1,
c: 1,
}
type ObjKey = keyof typeof obj // type ObjKey = string
方法1: 符合TS規(guī)范的書寫方式(非推導(dǎo),只是提前聲明)
type ObjKey = "a" | "b" | "c"
const obj: Record<ObjKey, number> = {
a: 1,
b: 1,
c: 1,
}
方法2:使用聲明函數(shù)(可推導(dǎo),但要寫一個(gè)與業(yè)務(wù)不相關(guān)的func)
function defineObj<T extends string>(obj: Record<T, number>) {
return obj
}
const obj = defineObj({
a: 1,
b: 1,
c: 1,
})
type ObjKey = keyof typeof obj // type ObjKey = "a" | "b" | "c"