Illustration
export interface IEventDef {
ready: any,
}
export interface IIPCMessage {
eventType: keyof IEventDef,
data: IEventDef[this['eventType']]
}
interface IMessageHandlers {
[eventName: keyof IEventDef]: (data: ) => void
}
Question
As per the illustration giving a string index signature for an interface! As below:
interface IMessageHandlers {
[eventName: keyof IEventDef]: (data: /*HOW_TO_REF_eventName*/) => void
}
How can we reference the eventName
in my example? Or the index property name! Of the same line
In my exact code I wanted to do this:
interface IMessageHandlers {
[eventName: keyof IEventDef]: (data: IEventDef[thisLineProp]) => void
}
Which would give a great affinity! any way?
To clear better I'll take this snippet below!
export interface IEventDef {
ready: any,
}
export interface IIPCMessage {
eventType: keyof IEventDef,
data: IEventDef[this['eventType']] // <<= here
}
In that example I was able to reference the same interface with this
keyword! Which allow great type affinity! And it allowed nice typing precision!
What about referencing and getting the property name of the same line from the index signature?
Update
I noticed that I just met the
An index signature parameter type must be either 'string' or 'number'.ts(1023)`
Error!
And I changed the code to
type IMessageHandlers = {
[eventName in keyof IEventDef]: (data: /*REF_THE_PROP_NAME?*/) => void
}
And I go with the question for this?
You are almost there actually.
eventName
holds the type you want.Playground Link