0

Why does typescript allows this code ?

class Test<T> {
    private value: T;
    public setValue(value: T): this {
        this.value = value;
        return this;
    }
}

const test = new Test();
test.setValue(5);

As i instantiate the generic Test class without specifying the generic argument, the test variable is of type Test<{}>.

I thought that {} was an empty type, how can it be assigned a number ?

Thanks

dou bret
  • 267
  • 2
  • 11
  • 2
    Essentially what's being asked is why `const t: {} = 5;` does not result in a compile error. See the linked to question for the answer. – David Sherret Nov 23 '18 at 14:35
  • Thank you, does this mean that `{}` is the same as `any` ? I mean i wouldn't expect `{}` to be structurally compliant with a `number`. – dou bret Nov 23 '18 at 14:41
  • 2
    No. One example: `any` is assignable to `number` (`const t: number = 5 as any;`), but `{}` is not assignable to `number` (`const t: number = 5 as {};`--compile error). Read more here: https://stackoverflow.com/questions/18961203/any-vs-object – David Sherret Nov 23 '18 at 14:44
  • That's more clear, thanks. The second link proved to be very helpful. – dou bret Nov 23 '18 at 14:53

0 Answers0