Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 = []){
      }
}
like image 396
cgcardona Avatar asked Oct 20 '12 18:10

cgcardona


2 Answers

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.

like image 94
Guffa Avatar answered Oct 18 '22 22:10

Guffa


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).
}
like image 23
Bill Ticehurst Avatar answered Oct 18 '22 23:10

Bill Ticehurst