We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Heterogeneous Arrays

If you can do it in JavaScript, you can model it in TypeScript. It might not always be pretty... but in this case it is!

In languages like Go, you can't have an array that contains different types - at least not without using something a bit more complex like a struct or an interface. But in TypeScript, we can just union the types!

// TypeScript infers the type as (string | number)[]
let lightsaberStyles = [1, 2, "double", "shoto"];

function describe(style: string | number): void {
  console.log(`Wield ${style} lightsaber`);
}

lightsaberStyles.forEach(describe);
// Wield 1 lightsaber
// Wield 2 lightsaber
// Wield double lightsaber
// Wield shoto lightsaber

Just use a pipe | to create union types. Easy!

Assignment

Complete the interpolateComment function. It accepts three parameters:

  • An id number
  • A comment string
  • A comments array of strings and numbers

It should find the first element in the comments array that equals id and replace just that element with the new comment.

Your function should mutate the comments array directly, rather than returning a new array.