When working with Typescript, there are 3 types that share similarities as they are composed of primitive types, maps, and arrays:
type Color1 = { [component: string]: number }
type Color2 = {
green: number
red: number
blue: number
}
interface Color3 {
green: number
red: number
blue: number
}
Is it possible to create a type that encompasses all of the definitions above?
The straightforward approach does not cover Color3
:
type JsonPrimitive = string | number | boolean | null
type JsonifiableObject = { [Key in string]?: Jsonifiable }
type JsonifiableArray = readonly Jsonifiable[]
type Jsonifiable = JsonPrimitive | JsonifiableObject | JsonifiableArray
const color1 = {green: 1, red: 2, blue: 3} as Color1 as Jsonifiable
const color2 = {green: 1, red: 2, blue: 3} as Color2 as Jsonifiable
const color3 = {green: 1, red: 2, blue: 3} as Color3 as Jsonifiable
This results in:
Conversion of type 'Color3' to type 'Jsonifiable' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
Type 'Color3' is not comparable to type 'JsonifiableObject'.
Index signature for type 'string' is missing in type 'Color3'.