I am trying write a function that can take an array or an object but running into these conflicts. How do I tell TS specifically not to look for length if something is an object or a property foo if its an array?
interface Stuff {
list: [] | Obj;
}
interface Obj {
foo: "bar"
}
function generateSomething(data:Stuff) {
console.log(data.list.length) // Property 'length' does not exist on type 'Obj'
console.log(data.list.foo) // Property 'foo' does not exist on type '[]'
}
typeof VARIABLEdatavariable until you're 100% certain it's either an array or an object, because otherwise Typescript can't guarantee type saftey.Array.isArray( data.list )in an if statement to distinguish between the two.[]is specifically the empty tuple type; an array which definitely has length0. Presumably in practice you'd want something more useful likestring[](a synonym forArray<string>).