在使用带有默认参数的泛型类型时,如果变量是用泛型类型声明的,我就会失go 推理的好处.
假设有以下类型:
type Attributes = Record<string, any>;
type Model<TAttributes extends Attributes = Attributes> = {
attributes: TAttributes;
};
function create<TModels extends Record<string, Model>>(
schemas: TModels
): TModels {
return schemas;
}
如果我使用Model
来输入对象,然后将该对象传递给我的泛型函数,那么如果我使用not来输入该对象,我将失go 获得的推理益处.如果将泛型参数传递到Model
类型,则它会按预期工作.如下所示:
const TodoWithGeneric: Model<{ name: string; finished: string }> = {
attributes: {
name: "string",
finished: "boolean"
}
};
const TodoWithoutGeneric: Model = {
attributes: {
name: "string",
finished: "boolean"
}
};
const withInference = create({
Todo: { attributes: { name: "string", finished: "boolean" } }
});
const withGenericsPassed = create({ Todo: TodoWithGeneric });
const withoutAttributesPassedToGeneric = create({
Todo: TodoWithoutGeneric
});
有没有一种类型脚本解决方案,可以仍然具有类型化对象声明的好处,without必须传递泛型参数,但在传递到函数后仍然保留不类型化/推理的好处?
理想情况下,我们应该在TodoWithoutGeneric
的声明上有打字脚本支持,但是当它传递到withoutAttributesPassedToGeneric
时,我们go 掉了Model
类型,并允许推理接管.
此问题中的组合代码片段设置在此沙箱中: Code Sandbox here个
withInference.Todo.attributes.
和withGenericsPassed.Todo.attributes.
具有可用的属性键,而withoutAttributesPassedToGeneric.Todo.attributes
(使用泛型键入)则没有.
谢谢!