Home > Blockchain >  How to use a property from an interface as an index type
How to use a property from an interface as an index type

Time:01-02

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:

TS Playground

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">
  • Related