[英]Typescript type hinting inside dot notation
I have the following interface: 我有以下界面:
export interface IRenderStruct {
type: string;
props: {
className?: string;
children?: (string | IRenderStruct) | (string | IRenderStruct)[];
[propName: string]: any;
};
}
So resulting objects may be nested inside via elm.props.children
. 因此,生成的对象可以通过
elm.props.children
嵌套在内部。 I am now creating some unit tests and in one case, I know that I will have a RenderStruct object as children of another. 我现在正在创建一些单元测试,在一种情况下,我知道我将拥有一个RenderStruct对象作为另一个对象的子对象。 No string as children, and also no array of RenderStruct objects as children.
没有字符串作为子项,也没有RenderStruct对象数组作为子项。
But when I want to do this: 但是当我想要这样做时:
expect(result.props.children.type === 'something');
The TS compiler complains that I cannot access type
because children
may be a string and that doesnt have the property type
. TS编译器抱怨我无法访问
type
因为children
可能是字符串,并且没有属性type
。
Okay, TS - you are correct! 好的,TS-你是对的! But I definitely know that in this case we will have the nested structure.
但我绝对知道,在这种情况下,我们将具有嵌套结构。 How do I tell TS that its the case?
我如何告诉TS这种情况?
Create an user-defined type guard to check it: 创建一个用户定义的类型防护以对其进行检查:
var render: IRenderStruct;
// function to check if something is an IRenderStruct:
function isIRenderStruct(p: any): p is IRenderStruct {
return ('props' in p) && ('type' in p);
}
let b: boolean;
if (isIRenderStruct(render.props.children)) {
b = render.props.children.type === 'something'; // No errors
}
EDIT : 编辑 :
For the specific case of your test, you can do: 对于测试的特定情况,您可以执行以下操作:
let test = false;
if (isIRenderStruct(render.props.children)) {
test = render.props.children.type === 'something'; // No errors
}
expect(test).toBeTruthy();
this way, you avoid else
s. 这样,您可以避免
else
。 If the guard fails, test
will be false
and your test will fail. 如果防护失败,则
test
将为false
并且您的测试将失败。 This way you can even get a broader range of errors. 这样,您甚至可以获得更多的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.