【发布时间】:2020-02-28 00:24:06
【问题描述】:
当约束一个类的泛型类型时,ts 抱怨泛型可以用不同的子类型实例化。任何人都知道这实际上意味着什么(以及如何处理它)?
复制(TypeScript 3.6.4):
interface BaseSchema {
readonly id: string;
}
class Model<GenericSchema extends BaseSchema> {
public test(): GenericSchema {
return { id: '' };
}
}
错误:
输入 '{ id: string; }' 不可分配给类型 'GenericSchema'。 '{ id:字符串; }' 可分配给类型的约束 'GenericSchema',但 'GenericSchema' 可以用 约束'BaseSchema'.ts(2322)的不同子类型
好像和https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-6.html#strict-function-types有关
我可以使它与类型断言一起工作,但它似乎不正确:
interface BaseSchema {
readonly id: string;
}
export class Model<GenericSchema extends BaseSchema> {
public test2(): GenericSchema {
return { id: '' } as GenericSchema;
}
}
更新:下面的新示例。在示例中,我们在实例化 Model 时提供了一个通用的 MySchema,这期望 test() 方法返回 MySchema。
class Model<
GenericSchema extends {
readonly id: string;
}
> {
public test() {
const dbResult: GenericSchema = { id: '' };
return dbResult;
}
}
interface MySchema {
readonly id: string;
readonly name: string;
}
const model = new Model<MySchema>();
const schema: MySchema = model.test();
这些都是人为的例子,真正的用例是访问数据库并返回我有类型注释的数据。本质上,MySchema 将代表数据库中的数据模型,所以我想将它作为一个泛型提供(因为 TS 不可能知道数据在数据库中的样子)。
【问题讨论】:
标签: typescript