How to solve the Type 'string' is not assignable to type '"AOI" | "DIMM" | "FAN" | undefined' ts error

Issue

I’m working on a vue3 project with TS and come across this error:
enter image description here

I have 3 potential values coming from my backend and my kind prop is looking for one of those 3 values as a string.

The prop itself looks like:
kind: { type: String as PropType<'AOI' | 'DIMM' | 'FAN'> }

Any idea as to why this error happens? The backend will only ever send one of those 3 values anyway, so I would assume this wouldn’t be an issue.

Please let me know if you need anymore context!

Cheers!

Solution

Is there not a way I can handle this issue on the frontend?

To be clear, I am not suggesting a change in the backend itself, but in the place you specify its signatures in the frontend.

But if you don’t want to change that, you can just add a type assertion someBackendMethod(...) as "AOI" | "DIMM | "FAN". Basically saying "I know that this particular string is one of these 3 even if the compiler doesn’t". But the problem is that if the backend then changes so it actually has another possible value, the compiler won’t tell you this place needs to be changed.

Another advice is to give some name to this union:

type SomeName = "AOI" | "DIMM | "FAN"

and then

kind: { type: String as PropType<SomeName> }

someBackendMethod(...) as SomeName

so at least if values are added/removed you only need to change one place.

Answered By – Alexey Romanov

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.