我想让typescript根据属性类型推断我的第二个参数"data"在我的第一个论点中。我已经为此挣扎了一段时间了,但没有成功。有关于如何设置type DialogHavingData
的提示吗?
type DialogHavingData<T> = /* Do know how to deal with this here*/
'data' in T ? T['data'] : any;
class MyDialog {
data: {
prop1: string;
prop2?: string;
prop3: {
name: string;
age?: number;
}
};
}
class MyDialog2 {
// data is optional
}
function createDialogFromClass<T = any, Y extends DialogHavingData<T>>(dClass: T, payload: Y) {
// implementation here...
}
// MyDialog specifies "data" property so my second argument should have the same type
createDialogFromClass(MyDialog, {
prop1: "my string",
prop3: {
name: "Test Name",
age: 12
}
// should ask me to provide prop1 and prop2 which would be the type of
})
// Any value is allowed because MyDialog2 doesn't specifiy the data property
createDialogFromClass(MyDialog2, null)
createDialogFromClass(MyDialog2, {test: "My test dialog"});
操场上联系
Typescript没有办法知道什么是T以及它有什么属性。要做到这一点,您必须提供某种常见的行为。你可以这样做:
type DialogStructure = { [key: string]: string | number }
type DialogWithData = { data?: DialogStructure }
这将支持所有遵循通用结构的类型,将允许对象的任何键为字符串,值为字符串或数字。如果data属性是可选的,则可以使用?帮助器让typescript知道它是否存在。
实现应该是这样的:
createDialogFromClass<T>(classInstance: T extends DialogStructure): DialogWithData
所以这里你用这个动态对象结构接受一个参数,并返回一个DialogWithData实例。