gpt4 book ai didi

TypeScript 需要一个参数或另一个参数,但两者都不需要

转载 作者:搜寻专家 更新时间:2023-10-30 20:32:38 24 4
gpt4 key购买 nike

假设我有这种类型:

export interface Opts {
paths?: string | Array<string>,
path?: string | Array<string>
}

我想告诉用户,他们必须传递路径或路径,但没有必要同时传递两者。现在的问题是这个编译:

export const foo = (o: Opts) => {};
foo({});

有谁知道允许 2 个或更多可选参数但至少 1 个是 TS 的必要参数?

最佳答案

你可以使用

export type Opts = { path: string | Array<string> } | { paths: string | Array<string> }

为了提高可读性,你可以这样写:

type StringOrArray = string | Array<string>;

type PathOpts = { path : StringOrArray };
type PathsOpts = { paths: StringOrArray };

export type Opts = PathOpts | PathsOpts;

关于TypeScript 需要一个参数或另一个参数,但两者都不需要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52132696/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com