I hav the following TypeScript code: type PropEventSource<Type> = { on<Key extends…
- User
I hav the following TypeScript code: type PropEventSource = { on<Key extends string & keyof Type> (eventName:
${Key}Changed, callback: (newValue: Type[Key]) => void): void; }; My question is why do we need to write it as Key extends string & keyof Type instead of Key extends keyof Type? - Assistant
In the TypeScript code, the reason for using
Key extends string & keyof Typeinstead ofKey extends keyof Typeis to ensure that the key is both a string and a key of the object typeType.Using
Key extends keyof Typewould allow any key from the object typeType. However, it would not guarantee that the key is a string. It might also be a number or a symbol, which could cause issues when trying to create an event name using a template literal.By using
Key extends string & keyof Type, you are enforcing that the key must be a string and a key of the object type . This way, you can safely create a string event name using a template literal, like , and ensure that the key is a valid property of the object type .
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.