gpt4 book ai didi

javascript - 错误 : Type '{}' is missing the following properties from type

转载 作者:行者123 更新时间:2023-12-04 14:37:24 33 4
gpt4 key购买 nike

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

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

当我声明 person1 时,我收到此错误:
Type '{}' is missing the following properties from type Person

最佳答案

这是一个更好的方法:

let person1: Person = {name: '', surname: ''};
但是,如果您想要完全为空的对象,则可以像这样破解它:
let person1: Person = {} as Person;
评论后更新:
看看这个 unpredictableFunction :
const unpredictableFunction = (): string|number|string[] => {
return Math.random() > 0.5 ? 'string' : Math.random() > 0.5 ? 9999 : ['1', '2', '3']
};
它可能返回数字,也可能返回字符串,也可能返回字符串数组
const person: Person = {name: '', surname: ''};
person.name = unpredictableFunction (); // this is a case you are talking about
在这种情况下,您会看到 Type 'string | number | string[]' is not assignable to type 'string'.答案是:
查看您的代码并确保仅将字符串分配给 Person 属性,
或者更新接口(interface)以准备好不同的值:
interface Person {
name: string | number | string[];
surname: string;
}

关于javascript - 错误 : Type '{}' is missing the following properties from type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60116708/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com