2

For instance, I have an abstract class:

type Tuple = [string, number]

abstract class SomeAbstractClass {
    tuples: Tuple[]
}

But when I want to implement this class

class SomeConcreteClass implements SomeAbstractClass {
    public tuples = [
        ['hello', 3],
        ['world', 4]
    ]
}

I am getting an error '(string | number)[][] is not assignable to Tuple[]'. How to tell Typescript that the array I provided actually satisfies the interface?

2
  • Give each array a type? public tuples = [ <Tuple>['hello', 3], <Tuple>['world', 4] ]; Commented Aug 5, 2021 at 12:14
  • Maybe it will work out, but it's a coercion, and Typescript suggests to convert it to 'unknown' first. This is a massive construction and I'd like to avoid that. Commented Aug 5, 2021 at 12:18

1 Answer 1

2

Just use explicit type:

type Tuple = [string, number]

abstract class SomeAbstractClass {
    tuples: Tuple[] = null as any
}

class SomeConcreteClass implements SomeAbstractClass {
    public tuples: Tuple[] = [
        ['hello', 3],
        ['world', 4]
    ]
}

SomeConcreteClass tuples property is mutable, hence TypeScript is unsure whehter it is assignable to abstract class tuples or not

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

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.