【发布时间】:2021-07-08 05:38:03
【问题描述】:
我有 Item<T> 和 StrictItem<T extends Something> 这样的课程。如果我将前者初始化为Item('a'),它将被视为Item<string>,而StrictItem<'a'> 将被视为StrictItem<'a'>。
- 为什么对泛型施加约束会导致这些差异?好像没有关系。
- 有没有办法改变
StrictItem的定义,所以StrictItem('a')将是StrictItem<string>,同时仍然保留对泛型的约束?
interface PlainObject<T> { [index: string ]: T}
type ItemValue =
boolean |
number |
string |
ItemValue[] |
{ [index: string ]: ItemValue } |
null;
class Item<T> {
private value: T;
constructor(value: T) {
this.value = value;
}
public set(value: T) {
this.value = value;
}
}
// This one puts restrictions on the generic
class StrictItem<T extends ItemValue> extends Item<T> {
}
// 1. Why does the error seen in item2 does not occur here?
let item1 = new Item('a');
item1.set('b');
item1.set(0); // error
// 1. Can StrictItem definition be modified to implictly infer a more
// general type ('string') in this case (without using any type for T)?
// Or is explicitly defining the type of passed value the only way (see item3)?
let item2 = new StrictItem('a');
item2.set('b'); // error
let item3 = new StrictItem('a' as string);
item3.set('b');
【问题讨论】:
-
你可以使用
new StrictItem<string>('a')
标签: javascript typescript typescript-typings typescript-generics