【发布时间】:2022-10-24 01:11:19
【问题描述】:
给定常量对象实现接口
interface Example {
item1?: {
item1?: string,
item2?: string,
},
item2?: {
item1?: string,
item2?: string,
}
}
const exampleObject: Example = {
item1: {
item1: 'test'
}
};
如何构造一个函数,该函数将接受此对象作为第一个参数,第二个参数将具有基于传递的对象的类型,而不是对象的接口?
function exampleFunction<T>(a: T, b: ??) { // <- how to define second parameter?
}
// correct - type exactly the same as first object
exampleFunction(exampleObject, {
item1: {
item1: 'test'
}
});
// incorrect - type not the same as the first object
exampleFunction(exampleObject, {
item1: {
item1: 'test',
item2: 'test'
}
});
// incorrect - type not the same as the first object
exampleFunction(exampleObject, {
item2: {}
});
// etc...
【问题讨论】:
-
您需要从
exampleObject中删除类型注释才能使其正常工作。 -
这现在是难以置信的明显。谢谢
-
这种方法的问题是我在 exampleObject 上失去了自动完成功能。所以问题实际上是,如何获得从实现 Example 接口的 exampleObject 派生的类型,但没有未指定的键,其中 Example 接口的所有键都是可选的。这是否可能,或者是否必须动态检查密钥是否匹配?
标签: typescript typescript-generics