0

I have User interface in typescript project (Ionic 2), and I want that one of his variables to have 2 different options as a type.

Example of what I written:

export interface User {
    _id: string,
    usUnits: boolean,
    height?: UsHeightUnits | NotUsHeightUnits
};

interface UsHeightUnits {
    feets?: number,
    inches?: number
}

interface NotUsHeightUnits {
    centimeters?: number
}

This not cause me any errors, the errors comes in another file:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { User } from '../../interfaces/user/user';

@Component({
    templateUrl: 'build/pages/profile-edit/profile-edit.html',
})
export class ProfileEditPage {
    public user: User;

    constructor(private navCtrl: NavController) {
        // Here i have red error underline, under the "centimeters"
        this.user.height.centimeters = 4;
    }
}

There error is: [ts] Property 'centimeters' does not exist on type 'UsHeightUnits | NotUsHeightUnits'.

In other cases with | (or) it works fine, like this case that using strings and not object:

export interface User {
    _id: string,
    gender: 'male' | 'female'
};

Suggestions?

1 Answer 1

1

A union type has all the properties that both types have in common.

For a better understanding look here: https://www.typescriptlang.org/docs/handbook/advanced-types.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.