给定类型和变量:
type Form = {
controls: {
[key: string]: any;
}
}
const form: Form = {
controls: {
firstName: {},
lastName: {},
},
};
我想要创建一个类型,它是一个包含form.controls
所有键的对象,其值类型为string
,即:
const formControlsWithStrings = {
firstName: 'foo',
lastName: 'bar',
};
我试过这样做:
type FormControlsWithStrings<T extends Form> =
{ [key in keyof T['controls']] : string }
但是,如果我在上面使用它来键入formControlsWithStrings
,它会强制使用string
值类型,但并不是这些键是等价的,-it不需要所有的键都存在,而且我可以添加新的键。
为什么这不起作用,我怎么才能让它起作用?
谢谢
Stackblitz:https://stackblitz.com/edit/typescript-sxvspk?file=index.ts
发布于 2022-09-14 06:48:21
这是因为form
的类型是Form
,它允许任何string
键。
如果让TS
推断form
的类型,那么它就会像预期的那样工作:
type Form = {
controls: {
[key: string]: any;
};
};
const form = {
controls: {
firstName: {},
lastName: {},
},
};
type FormControlsWithStrings<T extends Form> = {
[key in keyof T['controls']]: string;
};
const formControlsWithStrings: FormControlsWithStrings<typeof form> = {
firstName: 'abc',
// lastName: 'def' // should not compile when commmented as it a key of form
foo: 'bar', // should not compile as it is not present in form variable
};
https://stackoverflow.com/questions/73712489
复制相似问题