【问题标题】:How to force two types to be incompatible in TypeScript? [duplicate]如何在 TypeScript 中强制两种类型不兼容? [复制]
【发布时间】:2021-09-05 13:45:04
【问题描述】:

我想在 TypeScript 中创建两种类型,它们都是数字:

export type GlobalPortIndex = number;
export type TypePortIndex = number;

据我了解,TypeScript 会认为这些是相互兼容的,因为它们完全重叠。

但我希望它们不兼容,所以当我键入 GlobalPortIndex 时,如果我尝试为其分配 TypePortIndex,我会收到类型错误。这是为了确保我不会在代码中混淆它们,例如我不能将一个传递给需要另一个的函数。

有什么 TypeScript 技巧可以实现这一点吗?

【问题讨论】:

  • 您是否熟悉这里的艺术术语“nominal typing”,以及添加虚假非运行时属性作为“标签”或“品牌”的常见解决方案?

标签: typescript types typing


【解决方案1】:

我不是打字稿专家,但如果你真的将值包装到类中然后静态检查类类型不是更好吗?

由于您的对象类型看起来像是GlobalPortIndex,而另一个对象类型是TypePortIndex,它们的用途不同。

或者也许将它们设置为enum 语法可以解决这个问题?

enum FooKeys {
  FOO = 'foo',
  BAR = 'bar',
}

// probably all you need, but it's a type alias
type FooType = Record<FooKeys, string>;

以上代码引用自本帖:How to build a type from enum values in TypeScript?

【讨论】:

    【解决方案2】:

    您需要声明额外的属性(或方法)以使 2 个类不同:

    class GlobalPointerIndex extends Number {
      __GlobalPointerIndex: boolean;
    }
    
    class TypePortIndex extends Number {
      __TypePortIndex: boolean;
    }
    

    【讨论】:

      【解决方案3】:

      试试这个:

      export interface GlobalPortIndex {
      brand : 'GlobalPortIndex';
      value : number;
      }
      
      export interface TypePortIndex {
      brand : 'TypePortIndex';
      value : number;
      }
      

      但你必须像这样使用它:

      const myport = {value:25} as TypePortIndex
      

      并访问像myport.value这样的值

      【讨论】:

        猜你喜欢
        • 2017-01-03
        • 2011-03-09
        • 2020-05-12
        • 1970-01-01
        • 2019-06-05
        • 2018-10-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-17
        相关资源
        最近更新 更多