ashfaq.p
ashfaq.p

Reputation: 5469

Type string is not assignable to type

I am trying to create a constant which can only have two values as shown in code. And state.lang is already type-safe as en | ar.

const keyname: 'owner_name_en' | 'owner_name_ar' = 'owner_name_' + state.lang;

I am getting error like: Type 'string' is not assignable to type '"owner_name_en" | "owner_name_ar"'

How can I fix this error?

Upvotes: 3

Views: 2268

Answers (1)

msanford
msanford

Reputation: 12229

The reason is that you are declaring a new inline type (as a string enum) whose only possible values are 'owner_name_en' | 'owner_name_ar' (and null).

It is equivalent to

type OwnerNameLang = 'owner_name_en' | 'owner_name_ar';
const keyname: OwnerNameLang  = 'owner_name_' + state.lang;

Now, you can't concatenate different types this way any more than you could do this

const str: "hello" = "hel" + "lo"

hoping to get the unnamed inline type whose only possible values are null and "hello" (because the right-hand side of the assignment is also two <string> in your case).

You need to use type assertion, like

type OwnerNameLang = 'owner_name_en' | 'owner_name_ar';
const keyname: OwnerNameLang  = ('owner_name_' + state.lang) as OwnerNameLang ;

At this point, it may be preferable to use an an object with multiple decomposable properties (so that you can only store the en/ar as a string enum, and generate that string some other way). But without knowing more about the purpose of this string, it's hard to suggest a better alternative.

I'll add that I am a very strong supporter of type-safety, largely because it helps the developer notice when they, one day, discover a new state.lang and forget to handle it everywhere. Sometimes, though, a string is enough. Up to you to decide.

Upvotes: 4

Related Questions