我正在創建一種實用程式型別,該型別可以將多個明確指定的可選道具轉換為所需道具。
我可以使用自定義實用程式將單個可選道具轉換為所需道具,如下所示
type With<T, K extends keyof T> = T & { [P in K]-?: T[P] }
然后在代碼中使用 in 如下
type With<T, K extends keyof T> = T & { [P in K]-?: T[P] }
interface foo {
a?: 1
b?: 2
c?: 3
}
type fooWithA = With<foo, 'a'>
// equates into type: foo & {a:1}
所以效果很好。
但我無法理解如何一次轉換多個道具。我對型別映射不是很熟悉,我覺得研究對我沒有任何幫助。
這是我目前已設法組裝的多道具映射的(非作業)實用程式型別:
type WithMultiple<T, K extends (keyof T)[]> = T & {
[P in keyof K]-?: K[P] extends keyof T ? T[K[P]] : never
}
// not working how I would want it to
目前它的作用如下:
type WithMultiple<T, K extends (keyof T)[]> = T & {
[P in keyof K]-?: K[P] extends keyof T ? T[K[P]] : never
}
interface foo {
a?: 1
b?: 2
c?: 3
}
type fooWithAandB = WithMultiple<foo, ['a', 'b']>
// the type currently equates into: foo & [1 | undefined, 2 | undefined]
// even though I would need it to equate into something like: foo & {a:1, b:2}
什么可以為我指明正確的方向?我一直在網上搜索沒有真正的進展。
uj5u.com熱心網友回復:
只需使用您的原始型別并通過使用以下索引將陣列的專案作為聯合傳遞number:
type With<T, K extends keyof T> = T & { [P in K]-?: T[P] }
interface foo {
a?: 1
b?: 2
c?: 3
}
type fooWithA = With<foo, 'a'>;
type WithMultiple<T, K extends (keyof T)[]> = With<T, K[number]>;
type fooWithAB = WithMultiple<foo, ["a", "b"]>; // foo & { a: 1; b: 2; }
TypeScript Playground 鏈接
該陣列可以用字串文字鍵聯合替換,但是:
type With<T, K extends keyof T> = T & { [P in K]-?: T[P] }
interface Foo {
a?: 1
b?: 2
c?: 3
}
type FooWithA = With<Foo, 'a'>; // Foo & { a: 1; }
type FooWithAB = With<Foo, 'a' | 'b'>; // Foo & { a: 1; b: 2; }
TypeScript Playground 鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450786.html
