【问题标题】:TS Generic type for class including null valueTS 类的通用类型,包括空值
【发布时间】:2022-08-20 02:17:55
【问题描述】:

我从 API 接收数据,该数据的类型取决于其他一些信息或等于无效的(API 返回无效的如果没有价值)。我创建了泛型类(模型) 和几个扩展的类模型(样品1,样品2...)。如何定义需要类型 \'something\' 的泛型类或无效的?我想在类型中包含 null,因为我使用严格的 null 检查,这会很有帮助。

我的要求:

  1. 通用类
  2. 强制类型传递给泛型以包含 null
  3. 在所有类中使用严格的空检查
    type theType = null | {};
    
    class Model<Base extends theType> {
        public value: Base = null;
        public sthElse: Base = null;
        public defaultValue: Base = null;
    }
    
    class IDontWantThisApproach<Base...
    

    Playground Link

    标签: typescript typescript-generics


    【解决方案1】:

    让它可以为空!

    type Nullable<T> = T | null;
    
    class Model<Base extends theType> {
        public value: Nullable<Base>= null;
        public sthElse: Nullable<Base> = null;
        public defaultValue: Nullable<Base> = null;
    }
    

    Playground

    【讨论】:

    • 谢谢大家的回答,不过基本上和所有地方都加“|null”是一样的。没有更清洁的方法吗?
    【解决方案2】:

    这是与 Matthieu Riegler 相同的方法。但是您不必在每个字段上都写。 playground

    type theType = null | {};
    
    type Nullable<T> = T | null
    
    type CreateModel<M, Type> = {
      [K in keyof M]: M[K] extends Function ? M[K] : Nullable<Type>
    }
    
    class Model implements CreateModel<Model, theType> {
      public value = null
      public sthElse = null
      public defaultValue = {}
      public defaultValue = "null" //err
    
      h() {
        return null
      }
      m() {
        return "a"
      }
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-30
      • 2023-01-27
      • 1970-01-01
      • 2015-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多