Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.