繁星淼淼
问题的解决方案取决于您想要编程的场景!。以下是您的代码可能出现的一些情况。定义一个对象并从中推断其键。const persons = [ { name: "John", age: 12 }, { name: "Ben", age: 20 }];const fun = (info: typeof persons) => { //You will get intellisense here console.log(info[0].name);};您想要具有固定键的对象,在这种情况下可以使用类型和接口。interface IPerson { id?: string; // ID is optional (use of ? operator) name: string; // Name is Required age: number;}const persons: Array<IPerson> = [ { name: "John", age: 12 }, { name: "Ben", age: 20 }];// Both are same: Array<IPerson> === IPerson[]const fun = (info: Array<IPerson>) => { //You will get intellisense here console.log(info[0].name);};您想要拥有具有固定键的对象,并且想要提供部分信息。interface IPerson { id?: string; // ID is optional (use of ? operator) name: string; // Name is Required age: number;}const persons: Array<Partial<IPerson>> = [ { name: "John" }, // You can do it. { name: "Ben", age: 20 }];// Both are same: Array<IPerson> === IPerson[]const fun = (info: Partial<IPerson>[]) => { //You will get intellisense here console.log(info[0].name);};附加信息,Typescript 不支持运行时类型检查,仅支持编译时类型检查。对于运行时验证,您可以按如下方式实现该函数:const is_valid_person = (person: any): Boolean => { return ( typeof person === "object" && typeof person.name === "string" && typeof person.age === "number" && person.name.length >= 5 && person.age >= 1 );};console.log("Is person valid: ", is_valid_person({}));console.log("Is person valid: ", is_valid_person("Invalid Person"));我希望上述方法之一能够解决您的问题。就我而言,使用以下结构是正确的: obj: Array 或者我应该定义对象的每个键?上述问题的答案是:您可以使用上面显示的任何一种方法,因为 typescript 可以帮助您编写更好的代码并在编译时减少错误。一旦你的程序被编译,执行的代码就是纯 JavaScript。并且 JavaScript 不会验证您的响应。上述所有模式都会生成相同的JavaScript代码,因此不存在性能问题。
神不在的星期二
您可以创建自己的自定义对象类型:type CustomObject = { name: number age: number car1: number car2: number car3: number name4: number age4: number car41: number car42: number car34: number}const arrayOfCustomObjects: CustomObject[] = [{ name: 1, age: 2, car1: 8, car2: 8, car3: 8, name4: 1, age4: 2, car41: 8, car42: 8, car34: 8,},{ name: 1, age: 2, car1: 8, car2: 8, car3: 8, name4: 1, age4: 2, car41: 8, car42: 8, car34: 8,}]const fun = (objs: CustomObject[]) => { objs.forEach((obj) => { console.log(obj) })}fun(arrayOfCustomObjects)