打字稿创建用于将多个可选道具转换为必需道具的实用程序类型

Typescript creating a utility type for converting multiple optional props into required props

我正在创建一个实用程序类型,可以将多个明确指定的可选道具转换为必需的道具。

我可以使用自定义实用程序将单个可选道具转换为必需道具,如下所示

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}

这样效果很好。

但我无法理解如何一次转换多个道具。我对类型映射不是很熟悉,很遗憾,我觉得研究对我没有任何帮助。

这是我现在已经设法 assemble 的多道具映射的(非工作)实用程序类型:

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}

什么可以为我指明正确的方向? 我一直在网上搜索没有真正的进展。

只需使用您的原始类型并通过索引 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 Link

数组可以替换为字符串文字键联合,但是:

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 Link