Home > Back-end >  TypeScript: Exclude Union String Literal Value from Interface Key
TypeScript: Exclude Union String Literal Value from Interface Key

Time:01-18

I have an interface like this.

interface ITest {
  key1?: string;
  key2?: 'apple' | 'orange' | 'cherry' | 'grape';
}

Question

How can I extend ITest while excluding specific string literal values from the key2 union type?

I know I could use Exclude to remove key2 entirely, but how could I keep key2 but exclude specific values from its union type?

I have tried something like but with no luck. Not sure if this is possible with utility classes only without creating a separate Fruit type, for example and using Exclude on it.

Exclude<Pick<ITest, 'key2'>, 'apple' | 'grape'>

CodePudding user response:

  • take all properties except key2
  • add key2 with excluded elements
interface ITest {
  key1?: string;
  key2?: 'apple' | 'orange' | 'cherry' | 'grape';
}

type I2 = Omit<ITest, 'key2'> & {
  key2?: Exclude<ITest['key2'], 'apple' | 'grape'>
}

// alternative way
type I3 =  { 
  [P in keyof ITest]: P extends 'key2' 
  ? Exclude<ITest['key2'], 'apple' | 'grape'> 
  : ITest[P] 
}

Playground link

  •  Tags:  
  • Related