简体   繁体   English

打字稿中对象的通用类型数组

[英]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 .我不明白如何在inner function call没有收到type error I guess it has something to do with the generic .我想这与generic . Cant figure out a way of rewriting.想不出重写的方法。

The Datum interface is just too broad. Datum界面实在是太宽泛了。 It will represent basically any object (ie indexable by a string and the result of the indexing operation is any ).它将基本上代表任何对象(即可由字符串索引并且索引操作的结果是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.鉴于对象类型太宽, DatumDatum[]Datum[][]都可以分配给数组类型,因此您不会收到任何错误。 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:或者正如@PatrickRoberts 在评论中提到的,您可以向接口添加number索引以使其与数组明确不兼容:

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
};

The best option would probably be using directly the object interface instead of Datum :最好的选择可能是直接使用object接口而不是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. Pd:我一直在为同样的问题寻找解决方案,使用了@titian-cernicova-dragomir 的解决方案,效果很好。 I ended up finding the object interface being used in the react-csv library.我最终找到了在react-csv库中使用的对象接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM