我正在尋找這樣的東西......
type B = a ? 'apple' | 'grape' | 'orange' : 'apple' | 'grape'; // Of course, ERROR!
const x = (a: boolean, b: B) => console.log('foo')
我該如何實施?在打字稿中可以嗎?
uj5u.com熱心網友回復:
你確實可以。為此,您需要使用泛型和條件型別。像這樣:
type Type1 = "apple" | "grape" | "orange";
type Type2 = "apple" | "grape";
const x = <A extends boolean>(a: A, b: A extends true ? Type1 : Type2) =>
console.log("foo");
x(false, "orange"); // error
x(true, "orange"); // no error
uj5u.com熱心網友回復:
請檢查此打字稿檔案。 https://www.typescriptlang.org/docs/handbook/2/conditional-types.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/433058.html
標籤:打字稿
上一篇:來自混合物件陣列欄位的鍵聯合
下一篇:打字稿型別級別過濾
