簡體   English   中英

基於不同屬性的多種TypeScript判別

[英]Multiple TypeScript discriminations based on different properties

我正在嘗試構建一個支持不同用例的復雜 REACT 組件。 為了簡化它的使用,我想實現 TypeScript 區分類型以更好地推斷道具。

發布完整的示例沒有用,但我可以向您展示一個更簡單的示例,如下所示:

interface ICategoryDiscriminationGame {
    category: 'game';
    gameType: 'AAA' | 'AA' | 'A';
}

interface ICategoryDiscriminationProgram {
    category: 'program';
    programType: 'software' | 'freeware';
}

type TCategoryDiscrimination = (ICategoryDiscriminationGame | ICategoryDiscriminationProgram);


interface ISaleDiscriminationPresale {
    saleType: 'pre-sale',
    preSaleCost: number;
}

interface ISaleDiscriminationRetailSale {
    saleType: 'retail',
    retailSaleCost: number;
}

type TSaleDiscrimination = (ISaleDiscriminationPresale | ISaleDiscriminationRetailSale);


type TExampleCompProps = TCategoryDiscrimination & TSaleDiscrimination;

export const ExampleComp = (props: TExampleCompProps) => {
    if (props.category === 'game') { // In here, intellisense infer only use 'props.category' and 'props.saleType' -> NICE
        console.log(props.gameType); // In here, intellisense infer also 'props.gameType' -> NICE
    }

    if (props.saleType === 'pre-sale') { // In here, intellisense infer only use 'props.category' and 'props.saleType' -> NICE
        console.log(props.preSaleCost); // In here, intellisense infer also 'props.preSaleCost' -> NICE
    }

    if (props.category === 'game' && props.saleType === 'retail') { // In here, intellisense infer only use 'props.category' and 'props.saleType' -> NICE
        console.log(props.retailSaleCost); // In here, intellisense infer also 'props.retailSaleCost' and 'props.gameType' -> NICE
        console.log(props.gameType); // In here, intellisense infer also 'props.retailSaleCost' and 'props.gameType' -> NICE
    }

    return <p>In example comp</p>
}

如您所見,在ExampleComp內部,智能感知非常出色,而且效果很好。 問題是當我嘗試使用ExampleComp
我期望的是,當我編寫<ExampleComp時,智能感知只允許我使用 props categorysaleType ,因為如果不先定義這兩個,其他的就不能存在。 但是,相反,它只是暗示了一切:

在此處輸入圖像描述

所以,這里的問題是:我錯過了什么不能使智能感知在道具中也能正常工作?

TS Playground 鏈接

這就是 IntelliSense 的本質。 一旦您開始提供所需道具的一些組合,建議的組合將縮小到僅適用於當前可能組合的組合:

在添加一些道具之前: 在添加一些道具之前

添加一些道具后: 添加一些道具后

暫無
暫無

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

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