Kevin De Baerdemaeker

Typescript: Find Type from Array of Multiple Types

Modified 2022-09-23

type Kinds = KindA | KindB | KindC;

interface KindA {
    type: 'a';
    /* properties specific to A */
    hello: string;
}

interface KindB {
    type: 'b';
    /* properties specific to B */
    tellme: string;
}

interface KindC {
    type: 'c';
    /* properties specific to C */
    goodbye: string;
}

const getKindByType = <TType extends Kinds['type']>(
  kinds: Kinds[],
  kindType: TType,
) => {
  return kinds.find((k): k is Kinds & { type: TType } => k.type === kindType)
}

const kinds: Kinds[] = [{
    type: 'a',
    hello: 'there',
}, {
    type: 'b',
    tellme: 'no shouting',
}, {
    type: 'c',
    goodbye: 'cya',
}]

const a = getKindByType(kinds, 'a')
a?.hello // works = good
a?.tellme // doesn't work = good

References