这是与TypeScript中对象文字中的Type定义不同的问题
我有一个接受任何对象作为其属性之一的接口:
interface MyType {
/* ... */
options: any;
}
虽然该属性options
可以是任何东西,但有时我想指定某些类型。我不想使用'as'关键字,因为我不想强制它(如果我缺少属性,我想看到错误)。
这是我可以做到的一种方法:
interface MyTypeOptions {
hasName: boolean;
hasValue: boolean;
}
// Declare the options separately just so we can specify a type
const options: MyTypeOptions = {
hasName: false,
hasValue: true
};
const myType: MyType = {
/* ... */
options
}
但是有没有一种方法可以在myType
不使用类型断言的情况下将选项保持在对象文字内联的同时呢?换句话说,我想这样做:
const myType: MyType = {
/* ... */
// I want to type-check that the following value is of type MyTypeOptions
options: {
hasName: false,
hasValue: true
}
}
您正在寻找泛型。您可以使MyType
泛型并将其指定MyTypeOptions
为类型参数MyType
interface MyTypeOptions {
hasName: boolean;
hasValue: boolean;
}
// Declare the options separately just so we can specify a type
const options: MyTypeOptions = {
hasName: false,
hasValue: true
}
// We specify any as the default to T so we can also use MyType without a type parameter
interface MyType<T = any> {
/* ... */
options: T;
}
const myType: MyType<MyTypeOptions> = {
options: {
hasName: false,
hasValue: true
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句