cgcardona
cgcardona

Reputation: 121

How do I set the default value of a parameter to an empty array in TypeScript?

Regarding the following code I have two questions:

  1. When I compile it I get the warning/error "Cannot convert 'any[]' to 'Array'". Is that because public songPaths: Array = [] isn't legit and I should just go with public songPaths: any = [] ?

  2. Is Object an appropriate default value for public song:Object = new Audio()?

Example:

'use strict';

class Boombox{
      constructor(public track: number, public codec: string, public song:Object = new Audio(), public currentTime: number = 0, public playing:bool = false, public titles: any = [], public songPaths: Array = []){
      }
}

Upvotes: 11

Views: 15414

Answers (2)

Bill Ticehurst
Bill Ticehurst

Reputation: 1868

If 'Audio' is actually a type you want to use members of, then don't declare it to be type 'Object', as you will only have the members of Object available to you. Either declare it to be type 'any', or better yet, add an interface declaration for the members you want to use to get type checking. For example:

interface Audio { 
    listen: () => void;
};

function foo(x: Object, y: any, z: Audio) {
    x.listen(); // <-- Error: "The property 'listen' does not exist on type 'Object'"
    y.listen(); // <-- OK
    z.lisen();  // <-- Detects typo due to interface declaration and gives error "The property 'lisen' does not exist on type 'Audio'"
    z.listen(); // <-- Works fine (and gives you intellisense based on declaration).
}

Upvotes: 2

Guffa
Guffa

Reputation: 700372

To declare an untyped array, use any[] rather than Array:

public songPaths: any[] = []

You should specify the type if possible, for example:

public songPaths: string[] = []

You are not using Object as a default value. Object is the type and new Audio() is the default value. If possible the type should be the actual type that you want to use.

Upvotes: 12

Related Questions