Restricting Type Combinations in TypeScript

Viewed 88

I have two types:

type TypeLetter = "TypeA" | "TypeB"

type TypeNumber = "Type1" | "Type2"

I want to limit the ways I can combine values from these types so that only TypeA and Type1 can be together and only TypeB and Type2 can be together.

How can I create a type Restricted to make such a thing happen? In other words, where these are valid:

const valid1: Restricted = {
   valLetter: "TypeA" 
   valNumber: "Type1"
}

const valid2: Restricted = {
   valLetter: "TypeB" 
   valNumber: "Type2"
}

But this is not:

const nope: Restricted = {
   valLetter: "TypeB" 
   valNumber: "Type1"
}
1 Answers

The following would work for just those two. You can use const types.

type Restricted = {
    valLetter: 'TypeA',
    valNumber: 'Type1'
} | {
    valLetter: 'TypeB',
    valNumber: 'Type2'
};

const nope: Restricted = {
    valLetter: "TypeB",
    valNumber: "Type1"
} // Type '"Type1"' is not assignable to type '"Type2"'.
Related