简体   繁体   English

错误:类型“{}”缺少类型中的以下属性

[英]Error: Type '{}' is missing the following properties from type

interface Person {
  name: string;
  surname: string;
}
let person1: Person = {};

person1.name = "name"
person1.surname = "surname"

When I declare person1 I get this error:当我声明 person1 时,我收到此错误:

Type '{}' is missing the following properties from type Person

This is a better way:这是一个更好的方法:

let person1: Person = {name: '', surname: ''};

But if you want exactly empty object than you can hack it like this:但是,如果您想要完全为空的对象,则可以像这样破解它:

let person1: Person = {} as Person;

Update after comment:评论后更新:

Look at this unpredictableFunction :看看这个unpredictableFunction的函数:

const unpredictableFunction = (): string|number|string[] => {
  return Math.random() > 0.5 ? 'string' : Math.random() > 0.5 ? 9999 : ['1', '2', '3']
};

It may return number or it may return string or it may return array of strings它可能返回数字,也可能返回字符串,也可能返回字符串数组

const person: Person = {name: '', surname: ''};
person.name = unpredictableFunction (); // this is a case you are talking about

In this case you will see在这种情况下,您会看到

Type 'string | number | string[]' is not assignable to type 'string'.

Answers are:答案是:

Look at your code and ensure that you assign only strings to a Person properties,查看您的代码并确保仅将字符串分配给 Person 属性,

Or update interface to be ready to a different values:或者更新接口以准备好不同的值:

interface Person {
  name: string | number | string[];
  surname: string; 
}

You have defined an interface with two required properties.您已经定义了一个具有两个必需属性的接口。 So when you define an object with the type of the Person interface you must define these properties right away like this:因此,当您定义具有 Person 接口类型的对象时,您必须立即定义这些属性,如下所示:

let person: Person = {
    name: '',
    surname: ''
}

However if you believe these properties are not required but are rather optional you can change your interface to this:但是,如果您认为这些属性不是必需的而是可选的,您可以将界面更改为:

interface Person {
    name?: string;
    surname?: string;
}

Using the ?使用? syntax you mark the property as optional.您将属性标记为可选的语法。 The following code should then work:下面的代码应该可以工作:

let person: Person = {};

in Typescript 2.0 we can do this better在 Typescript 2.0 中我们可以做得更好

let person1 ! : Person;

this "!"这个 ”!” is Non-null assertion operator是非空断言运算符

according to documentation根据文档

A new !一个新的! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact.后缀表达式运算符可用于在类型检查器无法得出该事实的上下文中断言其操作数为非空且非未定义。 Specifically, the operation x!具体来说,操作 x! produces a value of the type of x with null and undefined excluded.产生一个 x 类型的值,其中排除了 null 和 undefined。 Similar to type assertions of the forms x and x as T, the !与 x 和 x 作为 T 形式的类型断言类似,! non-null assertion operator is simply removed in the emitted JavaScript code.非空断言运算符在发出的 JavaScript 代码中被简单地删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM