在 TypeScript 类型中使某些属性可选 [英] Make some properties optional in a TypeScript type
本文介绍了在 TypeScript 类型中使某些属性可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个具有所有必需属性的类型,我如何定义另一个具有相同属性的类型,其中一些属性仍然是必需的,但其余的都是可选的?
If I have a type with all required properties, how can I define another type with the same properties where some of it's properties are still required but the rest are optional?
例如,我想要一个从 SomeType 派生的新类型,其中 prop1 和 prop2 是必需的,但其余的都是可选的:
For example I want a new type derived from SomeType where prop1 and prop2 are required but the rest are optional:
interface SomeType {
prop1;
prop2;
prop3;
...
propn;
}
interface NewType {
prop1;
prop2;
prop3?;
...
propn?;
}
推荐答案
您可以使用 Partial
和 Pick
的组合使所有属性部分化,然后只选择一些必须:
You can use combination of Partial
and Pick
to make all properties partial and then pick only some that are required:
interface SomeType {
prop1: string;
prop2: string;
prop3: string;
propn: string;
}
type OptionalExceptFor<T, TRequired extends keyof T> = Partial<T> & Pick<T, TRequired>
type NewType = OptionalExceptFor<SomeType, 'prop1' | 'prop2'>
let o : NewType = {
prop1: "",
prop2: ""
}
这篇关于在 TypeScript 类型中使某些属性可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文