Skip to content

Literal not contextually narrowed when returned from an abstract methodΒ #55318

Closed as not planned
@ssalbdivad

Description

@ssalbdivad

πŸ”Ž Search Terms

symbol string number literal abstract narrow return class subclass

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried

⏯ Playground Link

https://www.typescriptlang.org/play?#code/MYewdgzgLgBGCuBbGBeGBWAsAKFJW0ATqjAEQBmIIpOe0MEAnsmgMrMBGIANgBQCUOHAEMORYcFjBuwiBBgAhWQFMYAbxwwtMUeMkwA5sqisohAJZgDAgFxlK1Tdt1mJsI1ABySDssK2MJy0XQjdDY3ZELj5+OyhGAAdlEHIGZiCdMVd9DwBhWShlABNI6ID4pJS0xBwAXyFcGTkYXIALc24imGUAD0KwIvklCFUNbG0YAHpJmABRQkIQQjsAFUTVAHIiSwMNmHN5MBBYWQhzAzBRblUoEBgKzYoqUg2Mj1MLKwF1DInCY3ghDADDMGXq2Ay0zmCyWq3WMA2CCifj2Bzgxx0cnOlw413udweCPQr3G2g83mR-n4P1JEy0-yggOBSLBDQmUPmi2WWjWSQRTCiPFRhwxp2xVxuBPhG3gYHMAEd4KoBdESRN3pweN8xnTtAymdVWRDaVMZpzYTzpSqhfsRScsRcJfj7tLZQqldVVW9jPloMVSlrqTrdaaYKxzIgOsJCNxGDBgAUdiDiEs4EhnQ8qkQYKnM6kkTB-hAkpJzAA3ZSxmBFEDKeT-RAgCv3VqqPxcgA0DAJ7XkI2UiHktxgvhgbsVkpbys13HjKl+eoBQOqmJdlVSAqN4KAA

πŸ’» Code

const num = 5
const str = "foo"
const sym = Symbol()

abstract class Base {
    abstract getString(): "foo"
    abstract getNumber(): 5
    abstract getSymbol(): typeof sym
    abstract getCastedSymbol(): typeof sym
}

class Child extends Base {
    // Error: Type 'string' is not assignable to type '"foo"'
    getString() {
        return str
    }

    // Error: Type 'number' is not assignable to type '5'
    getNumber() {
        return num
    }

    // Error:  Type 'symbol' is not assignable to type 'unique symbol'
    getSymbol() {
        return sym
    }

    // Error:  Type 'symbol' is not assignable to type 'unique symbol'
    getCastedSymbol() {
        // Similarly casting str or num to typeof str or typeof num respectively does remove the error, so this seems to be unique to the symbol case
        return sym as typeof sym
    }
}

πŸ™ Actual behavior

Return types were not contextually narrowed and allowed.

πŸ™‚ Expected behavior

Return types are contextually narrowed and allowed. Currently the best workaround is to add an explicit return annotation. Symbol case is possibly related to #53276, associated PR is #54778

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions