2016-09-14 65 views
0

我有User在typescript項目(Ionic 2)中的接口,我希望他的一個變量有2個不同的選項作爲類型。什麼我寫一些不同的對象作爲類型在界面 - Typescript

例子:

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

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

interface NotUsHeightUnits { 
    centimeters?: number 
} 

這不會引起我的任何錯誤,這些錯誤來自於另一個文件:

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; 
    } 
} 

有錯誤是:[ts] Property 'centimeters' does not exist on type 'UsHeightUnits | NotUsHeightUnits'.

在其他情況下與|(或)它工作正常,像這種情況下,使用字符串,而不是對象:

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

建議?

回答

相關問題