John McNeill
John McNeill

Reputation: 143

Typescript interface and object. Object type seems to be changing only when returned

I have initialized this object:

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

this.destinations = departureData;

using this interface:

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

I want to use the following function to extract the shuttleTime property but am getting results that I don't understand.

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

Upvotes: 0

Views: 37

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250066

There are several things wrong here, if departureData is of type Destination it should be initialized to an object ({}) not an array ([]). And I actually get a typescript error for this.

Secondly, if you are indexing into a Destiation object with destinations[str] the result will not be a Destination it will be the result of the indxer ({ locator: string, city: string, shuttleTime: string, option: string }). You can let the compiler infer this type for you, declare an interface for it and refer to that, or use a type query to get the type either version will do:

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

Upvotes: 1

Related Questions