首页 > 解决方案 > 打字稿:将某些属性标记为可选

问题描述

我正在寻找可以做到这一点的东西:

type MakeOptional<T, U> = /* ... */;

interface A {
  foo: string;
  bar: number;
  baz: Date;
}

type AWithOptionalFoo = MakeOptional<A, 'foo'>;
// result should be { foo?: string | undefined; bar: number; baz: number; }

type AWithOptionalBarAndBaz = MakeOptional<A, 'foo' | 'baz'>;
// result should be { foo?: string | undefined; bar: number; baz?: Date | undefined; }

这是我尝试过的...

type MakeOptional<T, U> = { [P in keyof T]: P extends U ? T[P] | undefined : T[P] }

...哪种有效,但它将这些属性标记为T | undefined而不是(optional)? T | undefined.

有任何想法吗?

标签: typescript

解决方案


您可以将Pick类型与类型结合使用Exclude以获取非可选键的类型,然后将其与映射类型相交,使其余部分成为可选(并将它们与 联合undefined)。

type MakeOptional<T, U extends keyof T> = Pick<T, Exclude<keyof T, U>> & {
    [K in U]?: T[K] | undefined;
}

或者,如果您不想要undefined联合,则可以只使用可选修饰符:

type MakeOptional<T, U extends keyof T> = Pick<T, Exclude<keyof T, U>> & Partial<Pick<T, U>>

然后,使用其中任何一个:

declare const test1: AWithOptionalFoo;
test1.foo // string | undefined
test1.bar // number
test1.baz // Date

// Note this is a misnomer, the type you defined for this uses "foo" and "baz".
declare const test2: AWithOptionalBarAndBaz;
test2.foo // string | undefined
test2.bar // number
test2.baz // Date | undefined

推荐阅读