I have the following statement in TypeScript:
let foo = {
bar: []
};
foo.bar.push("Hello World!");
However VSCode keeps complaining that this isn't allowed.
Argument of type 'string' is not assignable to parameter of type 'never'.ts(2345)
So I try to define the type as follows:
let foo = {
bar: Array<string>
};
But then I get the message that the method push is not allowed:
Property 'push' does not exist on type '{ (arrayLength: number): string[]; (...items: string[]): string[]; new (arrayLength: number): string[]; new (...items: string[]): string[]; isArray(arg: any): arg is any[]; readonly prototype: any[]; from(arrayLike: ArrayLike): T[]; from<T, U>(arrayLike: ArrayLike<...>, mapfn: (v: T, k: number) => U, thisArg?:...'.ts(2339)
Only way I found it to work was by defining it as follows:
let arr : Array<string> = [];
let foo = {
bar: arr
};
foo.bar.push('Hello World!')
Why can't I define the type inside the object itself? It seems cumbersome having to extract the types outside of it, into a variable.
let foo: { bar: Array<string> } = { bar: [] }no need to extract anything out. Just be explicit.expression of type '"Hello World!"' can't be used to index type '(...items: never[]) => number'error is because you used square brackets for thepushfunction callfoo.bar.push["Hello World!"]is trying to look up the property"Hello World!"on the objectfoo.bar.push, not call the functionfoo.bar.pushwith the argument"Hello World!".