【问题标题】:How to restrict the typescript T to be only primitive object如何将打字稿 T 限制为仅原始对象
【发布时间】:2020-11-17 18:51:06
【问题描述】:

昨天我问了这个问题How to restrict the typescript T to be only camplex object
现在我想知道如何实际做相反的事情?

class abstract MyClass<T> { }

我只想允许原始类型(字符串、布尔值等),例如:

class MyOtherClass extends MyClass<string> { } //<-- allowed

class MyOtherClass extends MyClass<IInterface> { } //<-- not allowed

实现这一目标的最佳方法是什么?

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    您可以创建您希望允许的自定义原始类型

    type IPrimitiveTypes = string | number | boolean;
    
    abstract class MyClass<T extends IPrimitiveTypes> { }
    

    Playground

    【讨论】:

    • 这是唯一的方法吗?
    • 就是这样。
    • 同样的答案,我不知道其他选择,但也许有人会提出其他建议:)
    【解决方案2】:
    type Primitive =
      | boolean
      | number
      | bigint
      | string
      | symbol
      | null
      | undefined;
    
    abstract class MyClass<T extends Primitive> { }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-02
      • 1970-01-01
      • 2021-11-25
      • 2017-01-04
      • 2018-07-27
      • 2020-11-04
      • 2019-05-31
      • 1970-01-01
      相关资源
      最近更新 更多