简体   繁体   中英

TypeScript: conditional type inside the same type/interface

Im trying to get some conditional typing to work and not sure if what Im thinking is possible to do or not. Here it goes:

type AParams = {
    hello: string

}
type BParams = {
    world: string
}

type Data = {
    name: "a" | "b",
    data: AParams | BParams
}

Depending on name being a or b I want to enforce the data to either have type AParams or BParams , respectively. Any way this can be accomplished with TypeScript?

You can use two different interfaces for the two cases like:

interface AData {
    name: "a",
    data: AParams
}

interface BData {
    name: "b",
    data: BParams
}

and then set Data using union types like:

type Data = AData | BData;

Your Data type can be next instead:

type Data = {
    name: "a"
    data: AParams
} | {
    name: "b"
    data: BParams
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM