typescript - 打字稿:将某些属性标记为可选
问题描述
我正在寻找可以做到这一点的东西:
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
.
有任何想法吗?
解决方案
您可以将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
推荐阅读
- microsoft-graph-api - 用于获取按上次修改过滤的聊天的 Teams Graph API 调用不返回最近的聊天
- api - 使用 PhpStorm 自动化 API 测试
- latex - 从 LaTeX 中的图形中删除(子)节号
- javascript - 从文件中读取随机行也会导入 \n?
- adobe - how to specify data file in adobe live cycle designer?
- javascript - 如何覆盖角度按钮单击的测试?(附上Stackblitz)
- ionic-framework - How to call rest api in background even when the app is closed in ionic for android platform?
- c++ - C++ - operator= self assignment checking
- winforms - 为从 PDF 转换为 PNG 的图像创建 zip 文件
- .htaccess - 将来自 /subdirectory 的请求重定向到 / 以转到 /subdirectory