Generic type array of objects in typescript

48
March 16, 2019, at 05:40 AM

Give then following:

interface Datum {
    [k: string]: any
}
type Data = Datum[]
const inner = (data: Data) => {
    console.log(data)
};

const outer = (data: Data | Data[]) => {
    inner(data) // expect type error?
};

I dont understand how I dont get a type error on the inner function call. I guess it has something to do with the generic. Cant figure out a way of rewriting.

Answer 1

The Datum interface is just too broad. It will represent basically any object (ie indexable by a string and the result of the indexing operation is any).

Given the object type is soo wide, both Datum and Datum[] and Datum[][] are assignable to an array type, and thus you don't get any error. Make the interface a bit more specific and you get an error. Ex:

interface Datum {
    [k: string]: boolean | number | string;
}
type Data = Datum[]
const inner = (data: Data) => {
    console.log(data)
};

const outer = (data: Data | Data[]) => {
    inner(data) // error now
};

Or as @PatrickRoberts mentions in comments you can add a number index to the interface to make it explicitly incompatible with an array:

interface Datum {
    [i: number]: never
    [k: string]: any;
}
type Data = Datum[]
const inner = (data: Data) => {
    console.log(data)
};

const outer = (data: Data | Data[]) => {
    inner(data) // error
};
READ ALSO
Doctrine2 - No foreign key inserted in the table with relation OneToMany(

Doctrine2 - No foreign key inserted in the table with relation OneToMany(

I have a problem with doctrine2 with a simple relationship between the two models Below I have prepared a simple example

25
How to manage complex class dependencies in PHP?

How to manage complex class dependencies in PHP?

I'm writing a PHP script that generates SVG plans for all the components that make up a pinball machine, to send to a laser cutterThere are many dozens of components

31
How can I insert a new column in my table using php and mysql?

How can I insert a new column in my table using php and mysql?

I'm trying to add the column "test" in my table "reservation" but it doesn't work

21
Getting error when trying to edit subpage in Grav

Getting error when trying to edit subpage in Grav

Whenever I try to add or edit a subpage (ie

45