
[英]How to discriminate union type by checking any object key in the union in TypeScript?
[英]Typescript fail checking for properties in the union of a function type and a object type
Typescript 无法检查 function 类型和 object 类型的联合中的属性,该类型与另一个对象联合和 ZC154F114252748E76 截获
这是重现该问题的最小存储库。 存档的正确方法是什么?
type Component = () => {};
type OneType =
| Component
| { component: Component }
| { getComponent: () => Component }
type AnotherType =
| Component
| ({ // static properties of Component
option?: string;
anotherOption?: string;
} & OneType);
type AnyObject = {
[name: string]: AnotherType
}
function aFunction(comps: AnyObject, name: string) {
const comp = comps[name];
// [ts] fail here: Property 'component' does not exist on type 'AnotherType'
if (comp.component) {
return comp.component;
}
// [ts] fail here: Property 'getComponent' does not exist on type 'AnotherType'
if (typeof comp.getComponent === 'function') {
return comp.getComponent();
}
return comp;
}
这是游乐场: 游乐场回购
Typescript仅允许您访问联合中的公共属性。 一个解决方案是使用in
型后卫来说服你所谈论的工会哪个成员的编译器。
type Component = () => {};
type OneType =
| Component
| { component: Component }
| { getComponent: () => Component }
type AnotherType =
| Component
| ({ // static properties of Component
option?: string;
anotherOption?: string;
} & OneType);
type AnyObject = {
[name: string]: AnotherType
}
function aFunction(comps: AnyObject, name: string) {
const comp = comps[name];
// ok
if ('component' in comp) {
return comp.component;
}
// ok
if ('getComponent' in comp && typeof comp.getComponent === 'function') {
return comp.getComponent();
}
return comp;
}
在启用了空检查的3.2中,您还可以在联合的所有成员上声明缺少的属性,但是将它们声明为可选的,如果类型为undefined
。 这将使您能够访问并集上的属性,并且由于它们的类型不重叠,因此Typescript会将其视为已区分的并集,并且在检查属性时会缩小预期的类型。
type Component = () => {};
type OneType =
| (Component & { component?: undefined, getComponent?: undefined})
| { component: Component }
| { getComponent: () => Component, component?: undefined}
type AnotherType =
| (Component & { component?: undefined, getComponent?: undefined})
| ({ // static properties of Component
option?: string;
anotherOption?: string;
} & OneType);
type AnyObject = {
[name: string]: AnotherType
}
function aFunction(comps: AnyObject, name: string) {
const comp = comps[name];
{
if (comp.component) {
return comp.component;
}
if (typeof comp.getComponent === 'function') {
return comp.getComponent();
}
return comp;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.