Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Subclass property inference fails with literal and tuple types #35151

Closed
shicks opened this issue Nov 17, 2019 · 2 comments
Closed

Subclass property inference fails with literal and tuple types #35151

shicks opened this issue Nov 17, 2019 · 2 comments

Comments

@shicks
Copy link
Contributor

shicks commented Nov 17, 2019

TypeScript Version: 3.8.0-dev.20191115

Search Terms:
subclass property inference string literal tuple type

Code

class Base {
  readonly x: 'a' | 'b' = 'a';
  readonly y: readonly [number, number] = [1, 2];
}

class Sub extends Base {
  x = 'b';
  y = [3, 4];
}

Expected behavior:

It should pass. The type checker should use the requirement from the base class to inform the subclass property inference, similar to how normal assignment works:

let x: 'a' | 'b' = 'a';
let y: readonly [number, number] = [1, 2];
x = 'b';
y = [3, 4];

Actual behavior:

(property) Sub.x: string
Property 'x' in type 'Sub' is not assignable to the same property in base type 'Base'.
  Type 'string' is not assignable to type '"a" | "b"'.(2416)

(property) Sub.y: number[]
Property 'y' in type 'Sub' is not assignable to the same property in base type 'Base'.
  Type 'number[]' is missing the following properties from type 'readonly [number, number]': 0, 1(2416)

Playground Link:

https://www.typescriptlang.org/play/#code/MYGwhgzhAEBCkFNoG8CwAoa0BOCwBMB7AOxAE9oAPALmgHIw7oAfegIyYF57GBuDLLgIly0MrSFFSFANrEArgFs2CbABpoC5aoC60bjICMGgEw7+6AL4YMoSDADK8ttASUALgmL4Y8CEjRMKn12OgssCgMAZg0AFnMMSyA

Related Issues:

None found

@dragomirtitian
Copy link
Contributor

dragomirtitian commented Nov 18, 2019

Properties are not contextually typed by the baseclass. The way it works is the class is typed independently and then checked against the base class.

Duplicate of: #3667
Related To: #23911, #6118, #10570

If you want tot avoid specifying the type again, using type queries could ease some of the pain:

class Base {
  x: 'a' | 'b' = 'a';
  y: readonly [number, number] = [1, 2];
}

class Sub extends Base {
  x: Base['x'] = 'b';
  y: Base['y'] = [3, 4];
}

Playground Link

@shicks
Copy link
Contributor Author

shicks commented Nov 18, 2019

Thanks for the reference. I guess I missed the keyword "contextual".

I'm happy to close this as a duplicate of #10570.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants