![](/img/trans.png)
[英]In Typescript, how can you make a prop optional depending on the a generic type?
[英]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.