1

I have this pretty simple code in TypeScript:

type SomeType = [number, number, number]; // Should be an array of exactly 3 numbers

interface IThing {
   someThing: SomeType
} 

abstract class SomeClass {
  abstract getThing(): IThing;
}

class ConcreteClass extends SomeClass {
    getThing() {
       return {
          someThing: [4, 2, 2];
       }
    }
}

In the concrete class, when I assign someThing to [4, 2, 2], Typescript complains that Type number[] is not assignable to type [number, number, number]. Why is this, and how else can I ensure that someThing is an array of only 3 numbers?

1 Answer 1

1

If you put in the type annotation on the return it works fine :

type SomeType = [number, number, number]; // Should be an array of exactly 3 numbers

interface IThing {
    someThing: SomeType
}

abstract class SomeClass {
    abstract getThing(): IThing;
}

class ConcreteClass extends SomeClass {
    getThing(): IThing { // annotation here 
        return {
            someThing: [4, 2, 2] // no error here
        }
    }
}

In the absence of a type annotation you are in the following case:

type SomeType = [number, number, number]; // Should be an array of exactly 3 numbers

let x: SomeType;
// Okay
x = [1,2,3];
// Not okay
let y = [1,2,3]; // inferred `number[]`
x = y;

i.e. the inferred return type is not compatible with the desired 3tupple type.

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

5 Comments

Yes, thank you! It's particularly odd to have to declare this explicitly. I wonder if there's any specific reason for it. Thanks anyway though!
In the absence of an annotation the return has to be inferred. Unfortunately it is inferred based on the body of the function (not the base class) and hence you get the future error.
Oh. Should this be considered a bug? Should I file an issue?
Not a bug. But you can file a feature request if you want. Probably not worth changing (complicating / maintaining) this in the compiler though
We tried typing inherited properties from the base class and it broke legacy code :( See github.com/Microsoft/TypeScript/pull/…

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.