简体   繁体   中英

How to define TS type for [key, val]?

How should I defined TS type for [key, val] pair returned from Object.entries ?

type objType = {
    one: string | null;
    two: string | null;
};

const obj: objType = {
    one: 'one',
    two: 'two',
};

Object.entries(obj).map(([key, val]) => {
    console.log(key, val);
});

EDIT: this was just a simplified example. The problem was in my code

Everything works as expected. Thanks everyone!

Do you mean define the types of the key/value pair of the .map parameters like this?

Object.entries(obj).map(([key, val]: [Type1, Type2]) => {
    console.log(key, val);
});

You can do it like that:

type objType = {
    [key: string]: string | null;
};

type objEntriesType = objType[];

const obj: objType = {
    one: 'one',
    two: 'two',
};

const result: objEntriesType[] = Object.entries(obj).map(([key, val]) => {
    console.log(key, val);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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