【发布时间】:2020-08-28 12:06:32
【问题描述】:
我想创建一个函数f,它接受一个字符串并创建一个对象,其中key 是唯一的字段集。
我还希望函数对接口A 进行类型检查,以确保key-字段是对象上唯一的必需字段。 (会有其他可选字段)。
问题:
是否可以表达A 类型以使函数f 有效——并且不会产生类型错误——并且在使用时仍然正确地对A 进行类型检查?
export function f<A extends { key: string }>(key: string): A {
return { key }; // This produces compile error TS2322: (see below)
}
// This be a few different interfaces, but they all have in common that
// the key-field is the only required field.
interface WithKey {
key: string;
ignoreMe?: string;
}
const result = f<WithKey>('myKey');
编译器错误:
TS2322:键入'{键:字符串; }' 不可分配给类型 'A'。 '{键:字符串; }' 可分配给“A”类型的约束,但“A”可以用约束“{ key: string;”的不同子类型来实例化。 }'。
【问题讨论】:
标签: typescript typescript-generics