[英]Is there a bug with the TypeScript compiler regarding generics, or am I missing something?
我遇到了一个问题,这似乎很难解决。 假设我有以下代码:
interface HasId {
id: string;
}
type Combiner<T> = {
[key in keyof T]: T[key];
}
function testfn<T extends HasId>(args: Combiner<T>) {
}
class Person<T extends HasId> implements HasId {
id: string;
test() {
testfn<T>({ id: this.id });
}
}
此代码只是示例,但不应有任何错误。 但是,问题出现在这条线附近:
testfn<T>({ id: this.id })
它总是,总是,总是在编译时抛出这个错误:
Argument of type '{ id: string; }' is not assignable to parameter of type 'Combiner<T>'
但问题是,错误是错误的。 { id: string }
符合Combiner
类型的规范!
不仅如此,在 VSCode 上,它还建议我在调用testfn
时添加id
属性,这让我相信这是编译器错误。
我错了,还是其他人也在处理这个错误?
编辑:
这是我的tsconfig.json
:
{
"compilerOptions": {
"strict": true,
"experimentalDecorators": true,
"module": "CommonJS",
"target": "ES2019",
"lib": ["ES2019"],
"rootDir": "./src",
"outDir": "./dist",
"esModuleInterop": true,
"strictPropertyInitialization": false
},
"include": [
"./src"
],
"exclude": [
"./node_modules",
"./dist"
]
}
问题在于以下表达式:
testfn<T>({ id: this.id });
不能保证字面值{ id: this.id }
扩展T
。 它确实扩展HasId
,但这还不够。
您可能不是在处理Person<HasId>
,而是在某个时候处理Person<{ id: 1, name: 'John' }>
,这就是发生错误的原因:
{ id: this.id }
不能分配给{ id: number; name: string }
{ id: number; name: string }
如果您只关心testFn
中的id
值,它不应该需要参数化类型T
,但它可能足以编写(这解决了问题):
function testfn(args: Combiner<HasId>) {
}
但是我不确定您打算如何处理之前依赖于T
的Combiner
类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.