I am new in TypeScript. I might be asking a rookie question. I have the following array of objects. I would like to sort it either by age or name. This question was asked before. I tried following after reading this answer. And this. I couldn't compile it in TypeScript.
sortData2() {
const testData: object[] = [
{
name: 'name 1',
age: 20,
sex: 'M',
height: 7.5
},
{
name: 'name 1',
age: 10,
sex: 'M',
height: 6.5
},
{
name: 'name 3',
age: 30,
sex: 'F',
height: 4.5
}
];
testData.sort( (a, b) => {
return compare(a, b);
});
function compare(a: number | string | object, b: number | string | object) {
// compiler error Property 'age' does not exist on type 'string | number | object'.
return (a.age < b.age ? -1 : 1);
}
console.log(testData);
}
How can I sort it? Thanks in advance!
object[]type: typescript will infer something betteraandbwouldn't benumber | string | objectonlyobject. And even then, you are better off defining an interface for your objects, so you can more accurately typecheck.interface Person {name: string, age: number, sex: 'F' | 'M, height: number }?