11

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 = []){
      }
}

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the quick response. string[] = [] was just was I was looking for. And yes you're right I was incorrect in calling Object my default value when it was in fact the type. Switching Object to Audio gives me the warning/error 'The name 'Audio' does not exist in the current scope' I'll need to figure out what the type of new Audio() is or go with Object Thanks again!
@cgcardona: Every object return the type object, even the built in ones. I get the same error when I try to use Audio as type. Using Object as type would be a resonable compromise if you can't figure out how to use Audio. An alternative would be to encapsulate the Audio object in a class, then you could use that as type.
2

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).
}

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.