The outcome of your question relies on the specific scenario you aim to program in! Presented below are a few potential scenarios utilizing your code.
Start by defining an object and inferring its keys from it.
const people = [
{ name: "Sarah", age: 30 },
{ name: "Alex", age: 25 }
];
const printInfo = (data: typeof people) => {
//Intellisense will be available here
console.log(data[0].name);
};
If you desire objects with fixed keys, types and interfaces can be utilized for that purpose.
interface IPerson {
id?: string; // ID is optional
name: string; // Name is required
age: number;
}
const persons: Array<IPerson> = [
{ name: "Sarah", age: 30 },
{ name: "Alex", age: 25 }
];
// Both statements are equivalent: Array<IPerson> === IPerson[]
const printInfo = (data: Array<IPerson>) => {
//Intellisense will be available here
console.log(data[0].name);
};
If you want an object with fixed keys but wish to provide partial information, check out the following example.
interface IPerson {
id?: string;
name: string;
age: number;
}
const persons: Array<Partial<IPerson>> = [
{ name: "Sarah" },
{ name: "Alex", age: 25 }
];
// Both statements are equivalent: Array<IPerson> === IPerson[]
const printInfo = (data: Partial<IPerson>[]) => {
//Intellisense will be available here
console.log(data[0].name);
};
Keep in mind, Typescript supports type checking at compile time only, not during runtime.
To implement runtime type validation, consider using the function provided below:
const isValidPerson = (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? ", isValidPerson({}));
console.log("Is person valid? ", isValidPerson("Invalid Person"));
Hopefully one of the approaches mentioned above will resolve your issue.
In my situation, is it correct to use the construction 'obj: Array' or should I define each key of my object?
The answer to the above question is:
You can utilize any of the methods shown above. Typescript aids in writing more precise code and reducing mistakes during compilation. Once compiled, your code transforms into plain Javascript, which does not validate your responses.
All presented patterns result in the same JavaScript
code, so there are no performance concerns.