【问题标题】:Typescript generics and String Literal Types: Argument of type "OnBlur" is not assignable to parameter of type "T"打字稿泛型和字符串文字类型:“OnBlur”类型的参数不可分配给“T”类型的参数
【发布时间】:2020-03-09 12:12:21
【问题描述】:

如果我在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>;
}

【问题讨论】:

    标签: typescript generics


    【解决方案1】:

    泛型类型中的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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-26
      • 2018-06-19
      • 1970-01-01
      • 2019-10-30
      • 1970-01-01
      • 2016-10-25
      • 1970-01-01
      相关资源
      最近更新 更多