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

w1jd8yoj  于 2023-03-13  发布在  TypeScript
关注(0)|答案(1)|浏览(128)

我是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

非常感谢帮助!

hfsqlsce

hfsqlsce1#

通过使用TypeScript's typeoftype-operator(与JavaScript的typeof运算符不同),您可以这样做,但是您还需要将let n1更改为const n1,因为当n1可变时,typeof n1number,而不是文本值。
就像这样:

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”。
如果你希望或者需要n1是可变的,那么你所要求的是不可能的,作为演示:

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

typeof n1必须number,因为parseInt返回number-这反过来意味着type Numbers_210 | 20 | 30 | number,这意味着let n2: Numbers_2 = 1230;是有效的。
如果你需要一个number类型的“input”变量,但仍然希望Numbers_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`
}

相关问题