Typescript接口和对象。对象类型似乎仅在返回时才改变

时间:2018-07-26 13:12:38

标签: typescript types interface casting

我已经初始化了这个对象:

export const departureData = [];
departureData["NRT"] = {locator: "NRT", city: "Narita", shuttleTime: "1:45", option: "away"};

this.destinations = departureData;

使用此界面:

export interface Destination {
[locator:string]:{
    locator: string,
    city: string,
    shuttleTime: string,
    option: string
}}

我想使用以下函数来提取ShuttleTime属性,但得到的结果我不明白。

reportTimeValue(str):string{
    console.log("str: ", str); //"NRT"

    console.log("destinations",this.destinations);//gives list of destinations mapped to locator

    let dest:Destination = this.destinations[str];
    console.log("dest: ", dest, "typeof:",typeof(dest));//{locator: "NRT", city: "Narita", shuttleTime: "1:45", option: "away"} typeof: object

    console.log("dest.shuttleTime: ", dest.shuttleTime, typeof(dest.shuttleTime));//1:45 string

    console.log("dest.shuttleTime.shuttleTime: ", dest.shuttleTime.shuttleTime, typeof(dest.shuttleTime.shuttleTime));//undefined undefined

    //return dest.shuttleTime; //GET ERROR -->Type {locator:string, city:string, shuttleTime: string, option:string} not assignable to type string

    return dest.shuttleTime.shuttleTime //works...
}

1 个答案:

答案 0 :(得分:1)

这里有些错误,如果departureData的类型为Destination,则应将其初始化为对象({})而不是数组([])。实际上,我为此遇到打字错误。

第二,如果您使用Destiation索引到destinations[str]对象,则结果将不是Destination,而将是索引器({ locator: string, city: string, shuttleTime: string, option: string })的结果。您可以让编译器为您推断此类型,为其声明一个接口并引用该类型,或者使用类型查询获取任一版本将执行的类型:

export interface Destination {
    [locator:string]:{
        locator: string,
        city: string,
        shuttleTime: string,
        option: string
    }}

const departureData: Destination = {};
departureData["NRT"] = {locator: "NRT", city: "Narita", shuttleTime: "1:45", option: "away"};
let destinations  =departureData

function  reportTimeValue(str: string):string{
    console.log("str: ", str); //"NRT"

    console.log("destinations",destinations);//gives list of destinations mapped to locator

    let dest:Destination[string] = destinations[str];
    console.log("dest: ", dest, "typeof:",typeof(dest));//{locator: "NRT", city: "Narita", shuttleTime: "1:45", option: "away"} typeof: object

    console.log("dest.shuttleTime: ", dest.shuttleTime, typeof(dest.shuttleTime));//1:45 string

    return dest.shuttleTime;
}