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

variance of subtyping #33234

Closed
xiaoxiangmoe opened this issue Sep 4, 2019 · 5 comments
Closed

variance of subtyping #33234

xiaoxiangmoe opened this issue Sep 4, 2019 · 5 comments
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed

Comments

@xiaoxiangmoe
Copy link
Contributor

TypeScript Version: 3.6

Search Terms:

subtyping invariant covariant

Read and write variance
read and write invariance
readonly covariance
writeonly contravariance

Code

interface a {
  foo?: string
}

interface b extends a { 
  foo: string // subtype of string | undefined
}

declare const b: b;

const a: a = b;

a.foo = undefined; // now b has property `foo:undefined`
console.log(b.foo);

Expected behavior:

Can't extends when property foo of b isn't readonly

Actual behavior:

It has no warning and no error

Playground Link:

Related Issues:

@AnyhowStep
Copy link
Contributor

#18770

@AnyhowStep
Copy link
Contributor

A not-so-great workaround at the moment is to just make all your properties readonly always, and treat everything as immutable.

I personally do that but it's unnerving that I can slip up and make a mistake, and not have the compiler tell me about it

@sandersn sandersn added the Design Limitation Constraints of the existing architecture prevent this from being fixed label Sep 4, 2019
@sandersn
Copy link
Member

sandersn commented Sep 4, 2019

I don't think we're likely to make extends sound with respect to variance. Many crusty old OO codebases violate it.

Intersection behaves better, so I'd recommend that over extends if you care about variance.

@AnyhowStep
Copy link
Contributor

Doesn't TS add new breaking behavior behind a flag?

Anything that relies on unsound extends can turn it off, and everyone else that wants more safety, and are masochistic can use the new flag

@kevinbarabash
Copy link

I'm curious if anyone's run into issues in real code arising from this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed
Projects
None yet
Development

No branches or pull requests

5 participants