網站搜尋

Typescript:使用變數的值創建自訂類型


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

你可以透過使用 TypeScript 的 typeof 型別運算子(這與 JavaScript 的 typeof 運算子不同),但你也需要將 let n1 改成 const n1,因為當 n1 可變時,typeof n1 是 number 而不是該字面值。

像這樣:

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_2 是 10 | 20 | 30 | number,這也意味著 let n2: Numbers_2=1230; 是有效且沒問題的。

如果你需要一個 number 型的「input」變量,但仍然希望 Numbers_2 被限制在一小組已知的可能值,那麼你需要明確地 縮小 它,像這樣:

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`
}