2

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?

2 Answers 2

3

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;
Sign up to request clarification or add additional context in comments.

Comments

0

Your Data type can be next instead:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.