้•œๅƒ็ซ™็‚น ยท ๆœฌ้กต็”ฑ็ฌฌไธ‰ๆ–น GitHub ๅช่ฏป้•œๅƒๆไพ›๏ผŒ้ž GitHub ๅฎ˜ๆ–น็ซ™็‚น๏ผŒไธๆŽฅๅ—ไปปไฝ•็™ปๅฝ•ๆˆ–ๅ‡ญๆฎ่พ“ๅ…ฅใ€‚ๅ‰ๅพ€ github.com
Skip to content

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

Description

๐Ÿ”Ž 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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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