Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
963 views
in Technique[技术] by (71.8m points)

object - In Typescript, how can I map the keys of an interface into an array of specific strings?

I get data from the server in the form of rows and columns. I want to generate a mapping of column header titles to the column header index.

For example, I want {firstName: 0, lastName: 1} in case the order later changes.

The thing I'd like to do is get Typescript to know what types to expect, but I can't get it to.

For example, it doesn't know that firstName is a valid property of columnHeaderIndices

interface TheData {
   firstName: string;
   lastName: string;
}

const columnHeaders = data.rows[0];
const columnHeaderIndices = columnHeaders.map((i, j) => ({[i]: j}));

const firstNameColumnIndex = columnHeaderIndices.firstName;  // No type information here!

let firstNameOfFirstDataRow = data.rows[1][firstNameColumnIndex]

How can I get typescript to let me map the keys of an interface into an array of specific strings ?

Here's a Minimal Reproducible Example

question from:https://stackoverflow.com/questions/65649280/in-typescript-how-can-i-map-the-keys-of-an-interface-into-an-array-of-specific

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think you are looking for this (not sure).

from Typescript 2.1 you can use the type record.

Usage:

interface TheData {
   firstName: string;
   lastName: string;
}


type YourTypeName = Record<number, TheData>
// or inverted
type YourTypeName = Record<TheData, number>
// or to make things optional
type YourTypeName = Partial<Record<number, TheData>>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...