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

Fields of class generic type constraint are not assignable anything but null or undefined without assertion #17317

Closed
seangwright opened this issue Jul 20, 2017 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@seangwright
Copy link

TypeScript Version: 2.4.1

Code
Typescript Playground

interface State {
    isReady: false;
}

// Does not work
class Base1<T extends State> {
    myState: Readonly<T> = { isReady: false }; // Nope
    myOtherState: T = { isReady: false }; // Nope
    mySecondState: T = null; // Sure!
    theThirdEstate: T = undefined // Ok!

    setState(state: Partial<T>) {
        this.myState = Object.assign(this.myState, state);
    }

    update() {
        this.setState({ isReady: false }); // Nope
    }
}

// Works with 'as T'
class Base2<T extends State> {
    myState: Readonly<T> = { isReady: false } as T;
    myOtherState: T = { isReady: false } as T;

    setState(state: Partial<T>) {
        this.myState = Object.assign(this.myState, state);
    }

    update() {
        this.setState({ isReady: false } as T);
    }
}

Expected behavior:
The constraint of T as having a property isReady is flowed through and { isReady: false } is considered to have the same shape as T and is valid for T, Partial<T> or Readonly<T> without having use the explicit type assertion.

Actual behavior:
Manual type assertion is required but then compiles. Null and undefined are the only valid values to assign these class fields.

I suppose I could also replace all references to T outside of the generic constraint with State but that's no fun.

@ikatyang
Copy link
Contributor

See #16985 (comment)

And if you enable the --strictNullChecks option, you'll see errors on null and undefined.

@seangwright
Copy link
Author

Thanks for the heads up - wouldn't have found that issue myself. I'll follow along there - this issue can be closed if needed.

@mhegazy mhegazy added the Duplicate An existing issue was already created label Aug 28, 2017
@mhegazy
Copy link
Contributor

mhegazy commented Sep 12, 2017

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@mhegazy mhegazy closed this as completed Sep 12, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants