I was wondering, if it's possible to ensure with Angular 12 / Typescript, that all objects within an array have the same properties, without declaring the properties explicitly (should be generic).
Here's an example of what I want to achieve:
// This should compile because all objects have the same properties
const correct = [
{firstname: 'Jack', lastname: 'Sanders'},
{firstname: 'Susanna', lastname: 'Marsaglia'},
{firstname: 'Walter', lastname: 'Walker'}
]
// This shouldn't compile because some object have different properties
const wrong = [
{firstname: 'Aline', lastname: 'Rose', phone: 'xxx-xxx-xx-xx'},
{firstname: 'Daniel', email: '[email protected]'},
{firstname: 'Louisa', email: '[email protected]'}
]
I was able to create an Interface which only allows properties with type string
, but I couldn't achieve the example above.
export interface Data {
[keys: string]: string
}
CodePudding user response:
function sameKeys(input) {
if (!input || input.length === 0) return;
const keys = new Set(Object.keys(input[0]));
return input.every((item) => Object.keys(item).every((key) => keys.has(key)));
}
If you want a compile time check, then doing a proper type definition makes sense have given in another answer. But that will only work if this data is hardcoded. if you are fetching it from backend it will not work as types are lost when the code is already build as javascript don't have types.
CodePudding user response:
You should achieve this by interface as below
interface IStructure {
firstname: string;
lastname: string;
}
const correct: Array<IStructure> = [
{firstname: 'Jack', lastname: 'Sanders'},
{firstname: 'Susanna', lastname: 'Marsaglia'},
{firstname: 'Walter', lastname: 'Walker'}
];
//wrong will throw error