最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - Make second argument of a function optional or required, based on the first argument type - Stack Overflow

programmeradmin0浏览0评论

How to make data arg optional only if cat argument is not 1 ?

export class MyClass<T extends 1 | 2 | 3>{
  constructor(
    public cat: T,
    public data?: T extends 1 ? string[] : undefined,
  ) {
    ...
  }
}

How to make data arg optional only if cat argument is not 1 ?

export class MyClass<T extends 1 | 2 | 3>{
  constructor(
    public cat: T,
    public data?: T extends 1 ? string[] : undefined,
  ) {
    ...
  }
}
Share Improve this question asked 2 days ago AlexAlex 68k185 gold badges459 silver badges650 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

You could go with overloads.

export class MyClass<T extends 1 | 2 | 3> {
  constructor(cat: 1, data: string[]);
  constructor(cat: Exclude<T, 1>);
  constructor(
    public cat: T,
    public data?: string[],
  ) {
    ...
  }
}

Playground

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论