0

I'm refactoring some TypeScript and have come across something that has me stuck.

In the code below, how does the "as" keyword convert a Map<number, Trip> into a "Trip" object? If it isn't then what is it doing?

public mergeBookings(bookingData: Immutable.Map<number, Booking>) {

    // merge bookings
    const bookings: Immutable.Map<number, Booking> = this.mergeBookingData(bookingData);

    // sort bookings
    const sortedBookings: Immutable.Map<number, Booking> = SortingService.sortBookings(bookings);

    // add bookings to trip
    const trip: Map<number, Trip> = this.setBookingData(sortedBookings);

    return trip as Trip;
}

An explanation on the keyword, how it works for maps and other objects and some documentation on it would be good but any information would help in maintaining this code base.

In particular I wanted to update the function definition to include the return type but need to be confident that it is indeed a "Trip" object. Example desired function definition below:

public mergeBookings(bookingData: Immutable.Map<number, Booking>): Trip {...}

I've looked around StackOverflow answers to this for TypeScript and a long google session for documentation hasn't turned up any help. As per tags this code is using:
TypeScript
Angular
Immutable.js

1
  • There's a chance that this piece of code is faulty. Unless Trip is a map itself, this line just cheats typing system and will result in runtime error. Commented Feb 18, 2018 at 7:44

1 Answer 1

1

as is just a cast operator. It doesn't do any conversion. It doesn't change trip in any way whatsoever. It's only purpose is to ask the typescript compiler to trust the programer and not produce an error message.

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.