我有一個這樣的界面。
interface ITest {
key1?: string;
key2?: 'apple' | 'orange' | 'cherry' | 'grape';
}
問題
如何在從聯合型別ITest中排除特定字串文字值的同時進行擴展?key2
我知道我可以Exclude用來完全洗掉key2,但我怎么能保留key2但從其聯合型別中排除特定值?
我嘗試過類似但沒有運氣的東西。不確定這是否僅適用于實用程式類而不創建單獨的Fruit型別,例如并Exclude在其上使用。
Exclude<Pick<ITest, 'key2'>, 'apple' | 'grape'>
uj5u.com熱心網友回復:
- 獲取除 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]
}
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/414466.html
標籤:
