Ask Your Question
1

When using bracket notation, why do I receive a TypeScript error stating that the type 'string' cannot be assigned to the type 'never'?

asked 2023-03-31 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-04-13 17:00:00 +0000

ladyg gravatar image

This error occurs when attempting to access a property of an object using bracket notation, but the object does not have a property with the specified key. In TypeScript, the type of the property accessed with bracket notation is inferred from the type of the key provided. If the key does not exist in the object, TypeScript assumes that the property type is "never".

To fix this error, you should make sure that the key you are accessing actually exists in the object. You can also use a type assertion to tell TypeScript the expected type of the property, like this:

const obj: { [key: string]: string } = { name: 'Alice' };
const key = 'age';

// Use a type assertion to tell TypeScript that the property type is string
const age = obj[key as keyof typeof obj] as string;

In this example, we use a type assertion to tell TypeScript that the key is actually of type keyof typeof obj, which is equivalent to the type of the keys in the obj object. We also tell TypeScript that the expected type of the property is string using a type assertion, so we avoid the "string cannot be assigned to never" error.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-03-31 11:00:00 +0000

Seen: 11 times

Last updated: Apr 13 '22