【问题标题】:Is there a way to select the opposite of a custom type in Angular?有没有办法在 Angular 中选择与自定义类型相反的类型?
【发布时间】:2019-10-06 18:44:39
【问题描述】:

有没有办法使用 Typescript 在变量中选择与自定义类型相反的类型?

当我这样定义类型时: type Result = 'table' | 'grid'; 那么任何类型为 Result 的变量都可以有“table”或“grid”。

有没有办法得到'table'的反义词,即'grid'?就像使用布尔值一样,例如:

let a = false;
// a is false
a = !a;
// a is true

不是确切的语法,使用 '!'运算符,但获得与某个自定义类型相反的相同想法?

【问题讨论】:

    标签: angular typescript types


    【解决方案1】:

    你可以有这样的类型:

    type Result = 'table' | 'grid';
    let table: Result = 'table';
    
    let other: Exclude<Result, typeof table> = 'grid';
    

    这里other 的类型将是grid,你不能给它分配任何其他东西。

    我认为您不能将其分配给变量,类型在运行时不存在。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-10
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      相关资源
      最近更新 更多