How to set the default value for a parameter to an empty array in TypeScript?

Regarding the following code, I have two questions:

  • When compiling, I get a warning / error β€œUnable to convert any [] 'to' Array '.” Is this because public songPaths: Array = [] not legal and I should just go with public songPaths: any = [] ?

  • Is Object 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 = []){ } } 
+6
source share
2 answers

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

 public songPaths: any[] = [] 

You should specify the type if possible, for example:

 public songPaths: string[] = [] 

You do not use Object as the 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.

+8
source

If "Audio" is actually the type you want to use, then do not declare it as the "Object" type, since you will only have Object members available to you. Either declare it the type "any", or better yet, add an interface declaration for the members you want to use to get type checking. For instance:

 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). } 
+1
source

Source: https://habr.com/ru/post/928192/


All Articles