打字稿泛型和字符串文字类型:类型“ OnBlur”的参数不能分配给类型“ T”的参数

时间:2019-11-13 16:28:34

标签: typescript generics

如果我指定我的InputValidatorBinding中的泛型采用字符串文字类型,而该泛型类型用于另一类(该泛型类型为字符串类型),那么为什么会出现编译错误?它们不是基本相同吗?唯一的区别是InputValidatorBinding的约束更严格,而EventAggregator的约束更宽松。反正有什么可以完成我想做的事情?

type TextboxEvents = 'OnBlur' | 'WhileTyping' | 'WhileTypingThrottled';
type FormEvents = 'OnFormSubmit';
type DatepickerEvents = 'OnSelectDate' | 'OnCloseCalendar';
type WhenToProcessRule = TextboxEvents | FormEvents | DatepickerEvents;

class EventAggregator<T extends string> {
}

class InputValidatorBinding<T = WhenToProcessRule> {
   protected readonly eventAggregator: EventAggregator<T>;
}

1 个答案:

答案 0 :(得分:0)

通用类型中的

T = SomeType引入了通用类型T的默认值,但绝没有约束T。因此T可以是任何类型。如果既要约束又要具有默认值,则需要extends=T extends SomeType = SomeType

type TextboxEvents = 'OnBlur' | 'WhileTyping' | 'WhileTypingThrottled';
type FormEvents = 'OnFormSubmit';
type DatepickerEvents = 'OnSelectDate' | 'OnCloseCalendar';
type WhenToProcessRule = TextboxEvents | FormEvents | DatepickerEvents;

class EventAggregator<T extends string> {
}

class InputValidatorBinding<T extends WhenToProcessRule = WhenToProcessRule> {
   protected readonly eventAggregator!: EventAggregator<T>;
}

Playground Link