我想创建一个函数 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.类型'{ key: string; }'不能分配给类型'A': 类型'{ key: string; }'不可分配给类型'A'。 '{ key: string; }'可分配给类型'A'的约束,但'A'可以用不同的约束子类型'{ key: string; }'实例化。
问题是,你的语句说它接受的类型必须有 key
的 string
而这个类型将被返回。
这意味着如果我把
{key: 1, requiredField: 5}
它返回相同的类型,我有 requiredField
.
但执行情况 return { key }
破坏了这个语句,因为它没有返回 requiredField
了。这就造成了TS2322。
export function f(key: string): { key: string } { // <- return type
return { key };
}
interface WithKey {
key: string;
ignoreMe?: string;
}
const result: WithKey = f('myKey');
result.key; // works
result.ignoreMe // works (undefined)