当我将接口的任何属性设置为可选时,并将其成员分配给其他变量,如下所示:

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 

我得到如下错误:

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

如何避免这个错误呢?


当前回答

如果你想拥有nullable属性,将你的接口更改为:

interface Person {
  name?:string | null,
  age?:string | null,
  gender?:string | null,
  occupation?:string | null,
 }

如果未定义不是这种情况,可以从属性名前面删除问号(?)。

其他回答

你可以这样做!

let name1:string = `${person.name}`;

但是记住name1可以是空字符串

如果你想拥有nullable属性,将你的接口更改为:

interface Person {
  name?:string | null,
  age?:string | null,
  gender?:string | null,
  occupation?:string | null,
 }

如果未定义不是这种情况,可以从属性名前面删除问号(?)。

  @Input()employee!:string ;
announced:boolean=false;
confirmed:boolean=false;
task:string="<topshiriq yo'q>";

  constructor(private taskService:TaskService ) {
    taskService.taskAnnon$.subscribe(
      task => {
        this.task=task;
        this.announced=true;
        this.confirmed=false;
      }
    )
  }

  ngOnInit(): void {
  }
  confirm(){
   this.confirmed=true
   this.taskService.confirimTask(this.employee);
  }
}

我认为使用Karol Majewski提到的Require非常好。另一种实现相同的方法是使用交集类型(实际上由Require在内部使用)

function getPerson(): Person & {name: string} {
  const person = {name:"John"};
  return person;
}

const person = getPerson();
const name1: string = person.name;

使用Require或交集类型的优点是,我们不会像非空断言操作符那样推翻typescript编译器。

你可以使用NonNullable实用程序类型:

例子

type T0 = NonNullable<string | number | undefined>;  // string | number
type T1 = NonNullable<string[] | null | undefined>;  // string[]

文档。