简体   繁体   中英

Restricting Type Combinations in TypeScript

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"
}

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"'.

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