Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent a variable key name in typescript interface?

interface Items {
    id: Item,
}

id is not optional but it will have different name

for example:

let items = {
34433ded : {name: "foo", price: 0.99},
14d433dee : {name: "bar", price: 1.99},
}
like image 418
SMH Avatar asked Dec 08 '16 18:12

SMH


People also ask

How do you name a variable in TypeScript?

The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable. Declare its type and value in one statement.

How do you define a type of object key in TypeScript?

Use the keyof typeof syntax to create a type from an object's keys, e.g. type Keys = keyof typeof person . The keyof typeof syntax returns a type that represents all of the object's keys as strings. Copied!

Is interface a keyword in TypeScript?

An interface is a keyword which is used to declare a TypeScript Interface. An interface_name is the name of the interface. An interface body contains variables and methods declarations.

What is key string in TypeScript?

The {[key: string]: string} syntax is an index signature in TypeScript and is used when we don't know all the names of a type's properties ahead of time, but know the shape of the values. The index signature in the examples means that when an the object is indexed with a string , it will return a string .


2 Answers

Something like:

interface Item {
    name: string;
    price: string;
}

type Items = { [id: string]: Item }

let items = {
    34433ded : {name: "foo", price: 0.99},
    14d433dee : {name: "bar", price: 1.99},
} as Items;
like image 66
Nitzan Tomer Avatar answered Oct 10 '22 21:10

Nitzan Tomer


You can achive this by following structure:

interface Items {
    [key: string]: Item;
}

Here is your fiddle.
But remember due to JSON specification your object keys should't begin with numbers or if they do - you have to wrap them in quotes (as I did in fiddle)

like image 30
eko24ive Avatar answered Oct 10 '22 19:10

eko24ive