我希望组件公开接受类型的常量对象(即枚举)的函数.假设这个型号是Test
.
如果该函数接受Record<string, Test>
,则名称和Test
个对象之间的关系将丢失.但是,如果您try 传递一个带有额外字段的对象,编译器将抛出TS2345
如果函数将接受泛型参数T
和extends Record<string, Test>
,则关系将被保存,但额外的字段不会再导致编译错误.
如果这是其他人使用的库方法,它将掩盖库用户因拼写错误而导致的全部错误.
在这两者之间有没有什么我怀念的 Select ?
type Test = {
field: number
}
function a(param: Record<string, Test>) {
return param;
}
function b<T extends Record<string, Test>>(param: T) {
return param;
}
const x = a({
first: {
field: 13,
notExists: -1, // TS2345: Object literal may only specify known properties, and not_exists does not exist in type Test
},
} as const);
const y = b({
first: {
field: 42,
notExists: -1, // I want this line to throw compile-time error
},
} as const);
type xa = typeof x['first']['field']; // number
type xb = typeof y['first']['field']; // 42
// And keep finding 42 instead of number in type above