Home > Back-end >  Referencing type of a type in Typescript
Referencing type of a type in Typescript

Time:10-15

I am trying to set an option parameter for ApexChart, the option is:

easing: "linear"

This doesn't work as easing can't be set to type of string, so I tried

easing: "linear" as ApexChart["animations"]["easing"],

However this throws the following error:

TS2339: Property 'easing' does not exist on type '{ enabled?: boolean | undefined; easing?: "linear" | "easein" | "easeout" | "easeinout" | undefined; speed?: number | undefined; animateGradually?: { enabled?: boolean | undefined; delay?: number | undefined; } | undefined; dynamicAnimation?: { ...; } | undefined; } | undefined'.

which is strange as the error seems to contradict itself.

This technique of specifying type appears to work when I index into type once, though in this situation where I had to index into animation, then easing, it appears to not.

Is there a solution using this strategy, or a better strategy to achieve what I want as opposed to simply declaring the parameter as any

CodePudding user response:

ApexChart["animations"] produces a union containing undefined. You can't index undefined with "easing", hence the error. You need to exclude undefined from the union.

easing: "linear" as Exclude<ApexChart["animations"], undefined>["easing"],
  • Related