wolfhoundjesse wolfhoundjesse - 1 year ago 69
TypeScript Question

Mapping from one union type to another in typescript

I've been enjoying union types in typescript, but I've just hit my first snag.

This is the member in question:

organizations: Organization[] | number[];

This is what I'm trying to do:

let orgs = organziations.map(org => org.id);

In other words, take this collection of and map it to its id so that I can have instead a collection of .

The error I get is [ts] Cannot invoke an expression whose type lacks a call signature. True, map doesn't know which of the types it is dealing with. Unfortunately, nothing I've tried thus far has helped map out.

Answer Source

You should use a type guard in order to test if the variable has the right type. For example:

interface Organization {
    id: string

function isOrganizationList(list: any[]): list is Organization[] {
    return list.length === 0 || list[0].id !== undefined

let organizations: Organization[] | number[],
    orgs: string[];

if (isOrganizationList(organizations))
    orgs = organizations.map(org => org.id);

Notice: you could write your own implementation of isOrganizationList with a more robust test.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download