Skip to content

Terrible trouble with Map #30807

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

Closed
isoftninja opened this issue Apr 8, 2019 · 2 comments
Closed

Terrible trouble with Map #30807

isoftninja opened this issue Apr 8, 2019 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@isoftninja
Copy link

isoftninja commented Apr 8, 2019

class T {
    static map = new Map<string, object>();
    static getInstanceById(id:string): object {
        if ( !T.map.has( id ) ) {
            T.map.set( id, {} );
        }

        return T.map.get( id ); // >>>
    }
}

/** <<<
 * TS2322: Type 'object | undefined' is not assignable to type 'object'.
 * Type 'undefined' is not assignable to type 'object'.
 */
// very bad!
class T0 {
    static map = new Map<string, object>();
    static getInstanceById(id:string): object {
        let result = T0.map.get( id );

        if ( !result ) {
            result = {};

            T0.map.set( id, result );
        }

        return result;
    }
}
// Good!
class T1 {
    static map = new Map<string, object>();
    static getInstanceById(id:string): object {
        return T1.map.has( id ) ? T1.map.get( id ) : T1.map.set( id, {} ).get( id );
    }
}

@nmain
Copy link

nmain commented Apr 8, 2019

Duplicate of #9619

Either use the T0 form or a ! type assertion, or perhaps encapsulate the login from T0 into some sort of getValueOrDefault helper function.

@DanielRosenwasser DanielRosenwasser added the Duplicate An existing issue was already created label Apr 8, 2019
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants