代码之家  ›  专栏  ›  技术社区  ›  Terio

Typescript:使用变量的值创建自定义类型

  •  0
  • Terio  · 技术社区  · 2 年前

    我是TS新手,我想创建一个自定义类型

    我希望有一个自定义类型(Numbers_2),它接受一些数字加上存储在某个变量(n1)中的值,并以Numbers_1的方式工作

    let n1 = 40;
    type Numbers_1 = 10 | 20 | 30 | 40;
    type Numbers_2 = 10 | 20 | 30 | n1; // 'n1' refers to a value, but is being used as a type here. Did you mean 'typeof n1'?
    let n2: Numbers_2 = 1230; // This line should signal a problem
    

    非常感谢您的帮助!

    1 回复  |  直到 2 年前
        1
  •  0
  •   Dai    2 年前

    可以 ,通过使用 TypeScript's typeof type-operator (这与JavaScript的不同 类型 操作员),但您还需要更改 let n1 const n1 因为当 n1 是可变的 typeof n1 number 而不是文字值。

    Like so :

    const n1 = 40;
    type Numbers_1 = 10 | 20 | 30 | 40;
    type Numbers_2 = 10 | 20 | 30 | typeof n1;
    let n2: Numbers_2 = 1230;
    

    …这将导致第4行出现错误,这是您所期望的:

    类型“1230”不可分配给类型“ Numbers_2 '.


    如果你想要或需要 第1页 要做到可变,那么您所要求的是不可能的,通过演示:

    let n1 = parseInt( prompt( "What is the answer to the Ultimate Question of Life, The Universe, and Everything?" ), 10 );
    
    type Numbers_1 = 10 | 20 | 30 | 40;
    type Numbers_2 = 10 | 20 | 30 | typeof n1; // `n1: number`
    
    let n2: Numbers_2 = 1230; // OK
    

    n1类型 成为 数字 因为 parseInt 回报 数字 -这反过来意味着 type Numbers_2 10 | 20 | 30 | number 这意味着 let n2: Numbers_2 = 1230; 是有效的。

    如果您需要 数字 -键入“input”变量,但仍需要 数字_2 被约束为一小组已知的可能值 you'll need to explicitly narrow it ,类似于:

    type TheAnswer = 42;
    type Numbers_2 = 10 | 20 | 30 | TheAnswer;
    
    function isNumbers2( x: number ) x is Numbers_2 {
        switch( number ) {
        case 10: case 20: case 30: case 42: return true;
        default: return false;
        }
    }
    
    //
    
    // `n1` has type `number`
    let n1 = parseInt( prompt( "What is the answer to the Ultimate Question of Life, The Universe, and Everything?" ), 10 );
    
    if( isNumbers2( n1 ) ) {
        // Only within the scope of this `if` statement, `n1` has type `Numbers_2`
    }