[英]TypeScript: How to type "if a this key is present, this other key must be too" without explicitly copying everything over
我有這樣的自定義類型(此代碼不起作用):
type MyType =
| {
foo: string;
}
| {
foo: string;
barPre: string;
barPost: string;
}
| {
foo: string;
quxPre: string;
quxPost: string;
}
| {
foo: string;
barPre: string;
barPost: string;
quxPre: string;
quxPost: string;
};
我基本上希望以下對象是有效的MyType
:
const myThing1: MyType = { foo: 'foo' };
const myThing2: MyType = { foo: 'foo', barPre: 'barPre', barPost: 'barPost' };
const myThing3: MyType = { foo: 'foo', quxPre: 'quxPre', quxPost: 'quxPost' };
const myThing4: MyType = {
foo: 'foo',
barPre: 'barPre',
barPost: 'barPost',
quxPre: 'quxPre',
quxPost: 'quxPost',
};
以下對象應該是無效的MyType
:
const myThing5: MyType = {}; // missing 'foo'
const myThing6: MyType = { barPre: 'barPre', barPost: 'barPost' }; // missing 'foo'
const myThing7: MyType = { foo: 'foo', barPre: 'barPre' }; // if `barPre` exists, `barPost` must, too.
const myThing8: MyType = { barPre: 'barPre', barPost: 'barPost', quxPre: 'quxPre', quxPost: 'quxPost' }
我得到了正確的類型提示,通過這樣輸入:
type MyType = {
foo: string;
} & ({
barPre?: undefined;
barPost?: undefined;
} | {
barPre: string;
barPost: string;
}) & ({
quxPre?: undefined;
quxPost?: undefined;
} | {
quxPre: string;
quxPost: string;
});
但這似乎很乏味。 有沒有更簡單的方法來實現這一目標?
這是由於 Typescript 對聯合所做的奇怪的額外屬性檢查。 請參閱https://github.com/microsoft/TypeScript/issues/36945
您可以定義一個嚴格的聯合類型,它至少在您的情況下有效。 我沒有認真嘗試過,但你可以在這里閱讀。
將 StrictUnion 類型定義為:
type UnionKeys<T> = T extends T ? keyof T : never
type StrictUnionHelper<T, TAll> = T extends T ? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, undefined>> : never
type StrictUnion<T> = StrictUnionHelper<T, T>
然后在你的工會中使用它
type MyType = StrictUnion<A | B | C | D>
然后它會按照您的預期報告錯誤 myThing5、6、7 和 8。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.