繁体   English   中英

打字稿:如果设置了通用类型,则需要可选道具

[英]Typescript: make optional prop required if generic type is set

我想做类似的事情

export interface Foobar {
  foo: string;
  bar?: any;
}

export interface Foobar<T> {
  bar: T;
}

,因此,如果未传递任何泛型类型,则bar是可选的道具,但是如果设置了bar ,则必须是泛型类型...即,我希望能够

const one: Foobar = { foo: 'foo' }; // bar is not required here
const two: Foobar<number> = { foo: 'foo', bar: 123 }; // `bar` is required here

上面的建议

'Foobar'的所有声明必须具有相同的类型参数。

是否可以通过其他方式实现这一目标?

我不确定您的用例是什么,但是如果您可以使用类型别名而不是接口,则可以将Foobar定义为:

type Foobar<T = never> = {
  foo: string;
} & ([T] extends [never] ? { bar?: any } : { bar: T });

如果没有指定,它将使用默认通用参数T设置为never ,并且使用条件类型根据T的类型选择可选bar或必需bar 它以您想要的方式工作:

const one: Foobar = { foo: "foo" }; // bar is not required here
const two: Foobar<number> = { foo: "foo", bar: 123 }; // `bar` is required here

希望能有所帮助; 祝好运!

链接到代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM