【发布时间】:2020-03-27 07:37:52
【问题描述】:
我正在尝试创建一组对通用T 进行操作的函数,这些函数必须实现和接口IDocument。虽然这通常似乎有效,但 TypeScript 似乎无法识别 T 必须具有 IDocument 的键。
这是一个最小的例子:
interface IDocument
{
_id: number;
}
function testGeneric<T>(v: { [P in keyof T]?: T[P] })
{ }
function testConstraint<T extends IDocument>(doc: T)
{
// this works
console.log(doc._id);
// this works
testGeneric<IDocument>({ _id: doc._id });
// this fails
// Argument of type '{ _id: number; }' is not assignable to parameter of type '{ [P in keyof T]?: T[P] | undefined; }'.
testGeneric<T>({ _id: doc._id });
}
您可以在 TypeScript 游乐场here 上现场观看。
我很困惑为什么这不起作用,因为在我的testConstraint 函数中似乎T 总是有一个_id 键,因为它必须实现IDocument。事实上,如果我使用T 参数并访问_id 属性,它就可以正常工作。
请注意,testGeneric 函数位于我不拥有的库中,因此我无法更改该签名。
我在这里做错了什么?我是否需要使用不同的约束来表达T 必须拥有IDocument 拥有的每个键?
【问题讨论】:
标签: typescript