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
The
keyof Typeis used to make sure thatKeyis one of the keys ofType.The
string &part is used to ensure thatKeyis a string. This is because TypeScript uses a structural type system where an object is considered of a certain type if it has at least the same properties.If you only extend
keyof Type, TypeScript would also allow numbers or symbols if they are used as keys inType. By usingstring & keyof Type, you make sure thatKeycan only be a string that is also a key of .
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.