[英]Avoid warnings when using jest to test that data corresponds to TypeScript types
In the example below I want to verify that the data actually gives med a project
with a property id
. 在下面的示例中,我想验证数据是否确实为med提供了一个具有属性
id
的project
。
test('getActiveProject => Project', async () => {
let previouslyOpenProject = await client.getActiveProject()
if (!previouslyOpenProject) {
previouslyOpenProject = await client.createProject();
}
let project = await client.getActiveProject();
expect(project.id).toBeGreaterThanOrEqual(1);
});
I get the following ts error message 我收到以下ts错误消息
[ts] Object is possibly 'null' (referring to project and the use of project.id)
[ts]对象可能为'null'(指project和project.id的使用)
What is a good course of action from here: 从这里开始有什么好的做法:
Result type fo getActiveProject
is Project | null
getActiveProject
结果类型是Project | null
Project | null
. Project | null
。 If you are sure that let project
is not null you can map it by let project = await client.getActiveProject() as Project;
如果确定
let project
不为null,则可以通过let project = await client.getActiveProject() as Project;
来映射它let project = await client.getActiveProject() as Project;
. 。
Also you can do something like this 你也可以做这样的事情
let project = await client.getActiveProject(); // without type mapping
if (project !== null) {
// here project will be Project type, not a Project | null
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.