【发布时间】:2017-09-18 04:05:36
【问题描述】:
我在尝试推断泛型类型的泛型参数时遇到了问题:
type Box <T extends object> = { value: T; }
function set <T extends object>(box: Box <T> , newValue: T): void {
box.value = newValue;
}
const bbox: Box <{ foo: string }> = {
value: {
foo: "bar"
}
};
set(bbox, {
foo: "baz"
}); // OK as expected
set(bbox, 42); // ERR as expected
set(bbox, {
bar: "baz"
}); // ERR as expected
set(bbox, {}); // OK, unexpected
set(bbox, { /* no autocomplete/intellisense is given here for valid props */ });
如果您提供 {} 作为参数,TypeScript 会推断 {} 作为函数的有效类型。这也意味着在编辑器中,没有为指定对象类型的字段提供自动完成,因为{} 匹配所有对象。
关于 TypeScript 如何推断泛型参数是否有顺序(即newValue 的推断覆盖Box<T> 的推断,并且任何对象都可以分配给{})?如果是这样,有没有办法避免这种情况?
你可以通过添加一个额外的参数来部分解决这个问题:
function set <T, TN extends T> (box: Box <T> , newValue: TN): T {
box.value = newValue;
return newValue;
}
const bbox: Box <{ foo: string }> = {
value: {
foo: "bar"
}
};
set(bbox, {}); // ERR, expected
set(bbox, { /* still no autocomplete/intellisense */ });
但是,您仍然没有收到任何自动完成/智能感知。我猜这是因为extends,以及您不再直接寻找T。
【问题讨论】:
标签: typescript generic-type-parameters