79487595

Date: 2025-03-05 20:22:21
Score: 1
Natty:
Report link

Given @jcalz link i was able to make it work (TS Playground link):

type A = {
    kind: "a"
    v: string
    f: (param: string) => void
}

type B = {
    kind: "b"
    v: number
    f: (param: number) => void
}

type RecordMap = { a: string, b: number };
type UnionRecord<K extends keyof RecordMap = keyof RecordMap> = { [P in K]: {
    kind: P,
    v: RecordMap[P],
    f: (v: RecordMap[P]) => void
}}[K];

Working example:

const instanceA: A = {
    kind: "a",
    v: "test",
    f: (param) => {
        console.log(param)
    }
}

const instanceB : B = {
    kind: "b",
    v: 4,
    f: (param) => {
        console.log(param)
    }
}



function j<K extends keyof RecordMap>(conf: UnionRecord<K>) {
    return conf.f(conf.v)
}
j(instanceA)
j(instanceB)

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @jcalzi
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: puntolino