1

Given:

class A<T extends {
  [k: string]: any
}> {
  private model: T

  constructor(model: T = {}) {
    this.model = model
  }
}

Why do i got an error stating

Type '{}' is not assignable to type 'T'.

Doesn't {} is assignable to

{ [k: string]: any }

Thank you.

2
  • This feels like a bug. Did you check the typescript issues list? Commented Apr 27, 2019 at 4:01
  • Constraints are lower bounds, not upper ones. Commented Apr 27, 2019 at 4:29

2 Answers 2

1

This is a correct error.

Your class says that this code is legal:

type MyType = {
    a: string;
    b: number;
}

const c = new A<MyType>();

But now you have an A whose model value does not have the required a and b properties.

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

Comments

0

This issue is described here. The solution to issue is as below

class A<T extends {
    [k: string]: any
}> {
    private model: T

    constructor(model: T = <T>{}) {
        this.model = model
    }
}

Using type cast in constructor is essential model: T = <T>{}

Then you cn instantiate class A with just

var instA = new A();
// instA.model will be {}

You may also read this It has links and discussions about similar issues.

2 Comments

Yes, i noticed this when trying to solve it. But i think it shouldn't be the answer because why would {} isn't assignable to {[k: string]?: any} in the first place.
I've made edit with lnks to github issue about this case

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.