Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic type array of objects in typescript

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.

like image 491
amwill04 Avatar asked Mar 14 '19 21:03

amwill04


2 Answers

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
};
like image 167
Titian Cernicova-Dragomir Avatar answered Nov 09 '22 23:11

Titian Cernicova-Dragomir


The best option would probably be using directly the object interface instead of Datum:

interface Datum {
    [k: string]: any
};
// This is an object interface.

type Data = object[]; // instead of Datum[]


const inner = (data: object[]) => {
    console.log(data)
};

Pd: I was looking for a solution for this same issue, used the solution from @titian-cernicova-dragomir which worked nicely. I ended up finding the object interface being used in the react-csv library.

like image 43
feralamillo Avatar answered Nov 10 '22 00:11

feralamillo