Hi I am quite new to typescript and I would like to type an object which contains arrays grouped by category, and I would like to type according to this.
const machines:IMachines = {
1: [{category:"core", serial:"110"}, {category:"core",serial:231}],
2: [{category:"style", serial:"114"}, {category:"style",serial:"239"}]
}
type IMachines = {
[key:number]:IMachine[]
}
type IMachine = {
category:string
serial: string
}
From here I would like to narrow the type, to make sure all Machines within the same array have the same "category" type.
For example, if I change the machine object so the machine with serial 239, has now type "core". That should throw TS error, because style and core are different cateogry types within the same array.
const machines:IMachines = {
1: [{category:"core", serial:"110"}, {category:"core",serial:231}],
2: [{category:"style", serial:"114"}, {category:"core",serial:"239"}]
}
==>This should throw error
I am not sure how to do it:
I would attempt something like:
type IMachines<T> = {
[key:number]:IMachine<T>[]
}
type IMachine<T> = {
category:TCategory<T>
serial: string
}
type TCategory<K> = K
This doesn't work but, I posted just to explain the idea of what I am trying to achieve.
Thank you very much