1

I've just stumbled across the following syntax in TypeScript

export interface OrderPool {
    [id: string]: Level3Order;
}

Could someone clarify what I am looking at?

Best I can understand is that this is an interface OrderPool which contains a property named Id of type string(array?) and something of type Level3Order????

What is the relationship of Level3Order to the property Id and is Id an array or single instance?

2 Answers 2

6

that means Objects that implement the interface OrderPool contain key/value pairs, where the key (called id in this case) is of type string and the value is of type Level3Order

for example this objects correctly implements the interface:

{
  'item1': new Level3Order,
  'anotherItem': new Level3Order
}

You could also have something like

export interface OrderPool {
  [id: number]: Level3Order;
}

example:

{
  1: new Level3Order(),
  5: new Level3Order()
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks heaps, This answer most clearly explains my question.
1

What it means is simply, "If you index into something of type OrderPool, you get back something of type Level3Order."

The type of the signature should always be string or number. The name of the parameter ("id") is immaterial.

Take a look at the example below to get a complete idea.

class Level3Order{
    public dummy : number = 0;
}

export interface OrderPool {
    [id :string]: Level3Order;
}

let pool : OrderPool ={}
pool["test"] = 5; //Error number is not assignable to Level3Order
pool["test"] = new Level3Order();  //Ok
pool["whatever"] = new Level3Order();  //Ok
pool.whatever =  new Level3Order(); //Still ok
pool["test"].dummy = 5; // Dummy is a property on Level3Order, Ok 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.