我正在尝试将接口的泛型类型包装起来,并将一个接口属性的数据传递给另一个。
也许通过一个示例更容易理解:
interface IExample {
model: () => Record<string, any>
evaluator: Record<string, () => boolean>
}
用例如下:
const example: IExample = {
model: () => {
// The content can be changed by the user
return {
k1: true,
k2: 'some content',
k3: [1, 2, 3]
}
},
evaluator: {
testEvaluator: function () {
/**
* This is where I would like to have an autocompletion
* So internally example.model() is called and
* the return value is passed as `this`-argument
*/
return this.k1 === true
}
}
}
如代码注释中所述,我想提供自动补全功能 当用户为评估人员编写代码时向用户展示
到目前为止,我尝试过的操作看起来像这样:
interface IExample<Model extends Record<string, any> = Record<string, any>> {
model: () => Data,
evaluator: <Record<string, (this: Data) => boolean>
}
这甚至可能吗?如果是这样:我真的很感谢任何提示。
答案 0 :(得分:0)
您与类型非常接近,问题在于打字稿不会对变量执行任何推断。如果在变量类型注释中设置类型,则这是最终类型。
要获得推理行为,您需要使用一个函数。函数可以具有额外的类型参数,编译器将根据实际的参数类型来推断这些参数:
interface IExample<Model extends Record<string, any>> {
model: () => Model,
evaluator: Record<string, (this: Model) => boolean>
}
function createExample<T>(o: IExample<T>) {
return o;
}
const example = createExample({
model: () => ({
k1: true,
k2: 'some content',
k3: [1, 2, 3]
}),
evaluator: {
testEvaluator: function () {
// this is { k1: boolean; k2: string; k3: number[]; }
return this.k1 === true
}
}
});