Property string with only two possible values

Viewed 1936

I have a model Participant which can have two types: Establishment or Provider:

export class Participant {
    id?: number;
    name?: string;
    ltype: 'Provider' | 'Establishment';


    get isProvider(): boolean {
        return this.ltype === 'Provider';
    }

    get isEstablishment(): boolean {
        return this.ltype === 'Establishment';
    }

    get opposite(): string {
        if (this.ltype === 'Provider') {
            return 'Establishment';
        }
        return 'Provider';
    }
}

All good, no error till here. But when I try to initialize it:

const filter: Participant = {
    ltype: 'Provider'
};

It throws:

Type '{ ltype: "Provider"; }' is not assignable to type 'Participant'.

Property 'isProvider' is missing in type '{ ltype: "Provider"; }'.

I can't get rid off the above error.

enter image description here

I don't think it matters, but this code is for an Angular 4 application.

Thanks in advance.

1 Answers

You're misunderstanding TypeScript classes.

Your object only has an ltype property; TypeScript does not magically insert the rest of the properties in your class.

Instead, you should add a constructor that takes one of those two strings and initializes ltype.

You can use TypeScript's public in the constructor list to both declare the property and the parameter for it, and automatically have the property initialized from the parameter:

class Participant {
    id?: number;
    name?: string;

    constructor(public ltype: 'Provider' | 'Establishment') {
    }

    get isProvider(): boolean {
        return this.ltype === 'Provider';
    }

    get isEstablishment(): boolean {
        return this.ltype === 'Establishment';
    }

    get opposite(): string {
        if (this.ltype === 'Provider') {
            return 'Establishment';
        }
        return 'Provider';
    }
}

const filter = new Participant('Provider');
console.log(filter.ltype); // 'Provider'

Live Example

Related