Reputation: 4754
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
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 Machine
s.
Upvotes: 2
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