1

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.

2 Answers 2

2

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"},
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

Thanks, my intentions are quite strange. I just want to use this as custom typed records and to use typescript tooling to check my types without compiling. I know I should use better tools like database but this is less painless for small datas :)

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.