interface Mapping {
"x": (a: string) => void
"y": (b: number) => void
}
interface In<T extends keyof Mapping> {
readonly name: T,
fn: Mapping[T]
}
const inHandlers: In<"x"> = {
name: "x",
fn(prop /* :string */) {}
}
someone knows how to get the typeof In["name"]
as the index type of Mapping
? so I don't have to write "x"
two times
I already tried and somehow prop
becomes any
interface In {
readonly name: keyof Mapping,
fn: Mapping[In["name"]]
}
const inHandlers: In<"x"> = {
name: "x",
fn(prop /* :any*/) {}
}
CodePudding user response:
You can use an identity function to constrain the parameter type:
function createMapping <T extends keyof Mapping>(mapping: In<T>): In<T> {
return mapping;
}
const xMapping = createMapping({
name: "x",
fn (prop) {} // prop is string
}); // xMapping is In<"x">
const yMapping = createMapping({
name: "y",
fn (prop) {} // prop is number
}); // yMapping is In<"y">