我有兩個介面如下:
interface Foo {
foo: string;
}
interface Bar {
prop1: string;
prop2: string;
}
我的目標是創建一種將這兩個界面鍵與它們之間的下劃線組合在一起的型別,如下所示:
type MergeKeys<A,B> = {
[P in keyof A '_' P2 in keyof B]: string;
};
type Result = MergeKeys<Foo,Bar>;
所以結果將是:
interface Result {
foo_prop1: string;
foo_prop2: string;
}
這甚至可能嗎?
uj5u.com熱心網友回復:
這是一種方法:
type MergeKeys<A, B> = { [P in
`${Exclude<keyof A, symbol>}_${Exclude<keyof B, symbol>}`
]: string; };
主要思想是使用模板文字型別來執行所需的字串連接。
唯一的問題是編譯器會拒絕更簡單的`${keyof A}_${keyof B}`
,因為 TypeScript支持symbol
不能通過模板文字序列化為字串的-valued 鍵。為了說服編譯器進行 serialize keyof A
,我們必須消除任何symbol
-valued 鍵存在的可能性。這就是實用Exclude<T, U>
程式型別的用武之地。該型別Exclude<keyof A, symbol>
將回傳所有不是s的鍵的聯合(因此您將獲得任何或文字型別,但沒有s)。A
symbol
string
number
symbol
好的,讓我們測驗一下:
type Result = MergeKeys<Foo, Bar>;
/* type Result = {
foo_prop1: string;
foo_prop2: string;
} */
看起來挺好的!
Playground 代碼鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470430.html
上一篇:switch陳述句中的泛型型別