簡體   English   中英

通過一個元組的類型進行打字稿元組細化?

[英]typescript tuple refinement via the type of one tuple?

似乎我可以使用空檢查( === null )來細化元組,但我不知道如何在類型檢查上細化它們。 這可能嗎? ts游樂場

// refining against null works
declare function fooA(): [string, null] | [null, string];
function A() {
    const x = fooA();

    if (x[0] === null) {
        const y = x[1]; // y = string
    }
}

// attempting to refine based on type = string, fails
declare function isString(x: any): x is string;
declare function fooB(): [string, number] | [number, string];
function B() {
    const x = fooB();

    if (isString(x[0])) {
        const y = x[1]; // y = string | number
    }
}

這是設計限制。 您可以使用值(例如null )來區分聯合成員並有條件地縮小類型,但您不能使用類型保護來執行此操作。 請參閱此TypeScript 問題(它是關於對象而不是元組,但機制是相同的)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM