确保至少提供了一个属性来发挥作用



我想将3个参数字符串中的任何一个传递给函数。以下是最好的方法吗?我在想是否有其他更优雅的方式。

function (a: Option1 | Option2 | Option3) {
// some code here
}
interface Option1 {
a: string
b?: string
c?: string
}
interface Option2 {
a?: string
b: string
c?: string
}
interface Option3 {
a?: string
b?: string
c: string
}

让我们使用映射类型来解决这个问题!对于每个键,我们应该使该键为必需键,而其他键为可选键。

要使其他所有内容都是可选的,我们可以省略并使用内置的Partial类型。

对于获取键,我们可以使用内置的Pick类型。

最后,对于想要的类型,我们将它们相交:

type AtLeastOne<T> = {
[K in keyof T]: Pick<T, K> & Partial<Omit<T, K>>;
}[keyof T];

你可以这样使用它:

type A = AtLeastOne<Option>; // create the possible types
function a(a: A) {} // and use it here

几个调用的例子:

a({}); // ! error
a({ a: "" });
a({ b: "" });
a({ c: "" });
a({ a: "", b: "" });
a({ a: "", b: "", c: "" });
a({ a: "", c: "" });
如您所见,您必须为函数提供至少一个属性。你自己试试吧。

我相信你想要的是这个?:

function (type: OptionType) {
// some code here
}
type OptionType = Option1 | Option2 | Option3;
interface Option1 {
a: string
b?: string
c?: string
}
interface Option2 {
a?: string
b: string
c?: string
}
interface Option3 {
a?: string
b?: string
c: string
}

最新更新