TypeScript:从接口键中排除联合字符串文字值

TypeScript: Exclude Union String Literal Value from Interface Key

我有这样的界面。

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

问题

如何在从 key2 联合类型中排除特定字符串文字值的同时扩展 ITest

我知道我可以使用 Exclude 完全删除 key2,但我如何保留 key2 但从其联合类型中排除特定值?

我尝试过类似的方法,但没有成功。不确定这是否可以仅使用实用程序 类 而无需创建单独的 Fruit 类型,例如并在其上使用 Exclude

Exclude<Pick<ITest, 'key2'>, 'apple' | 'grape'>
  • 获取除 key2 之外的所有属性
  • 添加带有排除元素的 key2
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