如果我指定我的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>;
}
答案 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>;
}