打字稿:输入“字符串"|undefined' 不可分配给类型 'string' [英] Typescript: Type 'string | undefined' is not assignable to type 'string'

查看:79
本文介绍了打字稿:输入“字符串"|undefined' 不可分配给类型 'string'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将接口的任何属性设置为可选时,我在将其成员分配给其他变量时收到如下错误:

When I make any property of an interface optional, I get an error like the following while assigning its member to some other variable:

    TS2322: Type 'string | undefined' is not assignable to type 'string'.
    Type 'undefined' is not assignable to type 'string'.

    interface Person {
      name?: string,
      age?: string,
      gender?: string,
      occupation?: string,
    }
    
    function getPerson() {
      let person = <Person>{name:"John"};
      return person;
    }

    let person: Person = getPerson();
    let name1: string = person.name; // <<< Error here 

我该如何解决这个错误?

How do I get around this error?

推荐答案

您现在可以使用 非空断言运算符,它正好适合您的用例.

You can now use the non-null assertion operator that is here exactly for your use case.

它告诉 TypeScript,即使某些东西看起来可能为 null,它也可以相信你它不是:

It tells TypeScript that even though something looks like it could be null, it can trust you that it's not:

let name1:string = person.name!; 
//                            ^ note the exclamation mark here  

这篇关于打字稿:输入“字符串"|undefined' 不可分配给类型 'string'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆