Pavel Hanpari
Pavel Hanpari

Reputation: 4754

How define types of objects in Typescript?

I have following code:

type Machine = {
    id: string,
    name: string,
    tonnage?: number
}

const machines = {
    "machine1": {id: "S01", name: "AnyMachine"} as Machine,
}

is possible to indicate that key is string and value is typeof Machine? Casting as Machine seems to work, but I would like to have less verbose alternative.

Upvotes: 1

Views: 52

Answers (2)

Nitzan Tomer
Nitzan Tomer

Reputation: 164437

You can do this:

type Machines = {
    [key: string]: Machine;
}

const machines: Machines = {
    "machine1": { id: "S01", name: "AnyMachine" }
}

But, depending on what you're trying to do, it might not be necessary.
The Typescript type system is based on the structure of the types, so you can just do this and it will work:

const machines = {
    "machine1": { id: "S01", name: "AnyMachine" }
}

function fn(machine: Machine) {
    // ...
}

fn(machines.machine1);

Here the compiler infers that you're passing the right type even though machines isn't defined as a map of Machines.

Upvotes: 2

Aron
Aron

Reputation: 9258

You can do something like this:

interface MachineHolder {
  [key: string]: Machine;
}

type Machine = {
  id: string,
  name: string,
  tonnage?: number
}

const machines: MachineHolder = {
  "machine1": {id: "S01", name: "AnyMachine"},
}

Upvotes: 2

Related Questions