【发布时间】:2023-01-12 20:34:09
【问题描述】:
我无法理解 TypeScript Generic with classes 的这种行为。
打字稿
interface IProvider<K extends {[key: string]: any}> {
data: K;
}
class Provider<T extends {[key: string]: any}> implements IProvider<T> {
data: T;
constructor(arg?: T) {
this.data = arg || {}; // This is not allowed.
}
}
type User = {
[key: string]: any
}
const x = new Provider<User>();
错误是:
Type 'T | {}' is not assignable to type 'T'.
'T | {}' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{ [key: string]: any; }'.
Type '{}' is not assignable to type 'T'.
'{}' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{ [key: string]: any; }'.
但是,如果我删除可选运算符,它就可以正常工作。
打字稿
class Provider<T extends {[key: string]: any}> implements IProvider<T> {
data: T;
constructor(arg: T) { // no optional
this.data = arg || {}; // Now it works.
}
}
请帮我解释一下。非常感谢你!
【问题讨论】:
标签: typescript class generics constraints