Skip to content

Assertion functions don't work when defined as methods #36931

@mlhaufe

Description

@mlhaufe

TypeScript Version:

3.9.0-dev.20200220

Search Terms:

assertion signature

Code

type Constructor<T> = new (...args: any[]) => T

let str: any = 'foo'

str.toUpperCase() // str is any

function assert(condition: unknown, message: string = 'Assertion failure', ErrorConstructor: Constructor<Error> = AssertionError): asserts condition {
    if(!condition) {
        throw new ErrorConstructor(message);
    }
}

assert(typeof str == 'string')

str.toUpperCase() // str is string

class AssertionError extends Error { }

class Assertion {
    assert(condition: unknown, message: string = 'Assertion failure', ErrorConstructor: Constructor<Error> = AssertionError): asserts condition {
        if(condition) {
            throw new ErrorConstructor(message);
        }
    }
}

let azzert = new Assertion().assert

let str2: any = 'bar'

azzert(typeof str2 == 'string')  //error 2775

str2.toUpperCase() // str2 is any

Expected behavior:

Assertion functions are usable as methods of a class

Actual behavior:

Assertions require every name in the call target to be declared with an explicit type annotation.(2775)
'azzert' needs an explicit type annotation.

Playground Link:

https://www.typescriptlang.org/play/?ts=3.9.0-dev.20200220&ssl=1&ssc=1&pln=33&pc=34#code/C4TwDgpgBAwg9gOwM7AE4FcDGw6oDwAqAfFALxQIQDuUAFAHSMCGqA5kgFxRMIgDaAXQCUZEgQCwAKCkAbCMCgpUXHiDJQA5ADM4cDVKlL6OAKphIqGEyQRaIgPT3FaKAEsk3Xgclb0CbK6I3Eg2qMC0mIgAJq7AgQhcfgDWCHBUCAA0UAC2ECFMrBBcSq4IrOoaAIIhEGHxUFpMrjLoqBAaWQCiqKi48MhoWDjKsIhKQ7h43b2oJOTVoXGI07hCKjVhHpEIMUsIUADeUlAnblq0AITbu-EiR5Knj1DAABa9NJQ0K5Zjg9i4tFy+UKQgA3MdTgBfKTQ6SSayLWigSBwLTOVBkcgaEplDRCbxGUzmWpWGx2KCOdFuDw41jeTAyBFQBa1PbfKAQAAewAgOw87IOUFhUgZTJZdSC90eCNZEWisXiiQQKTSmRyeSQBSK6NK5Sx4r2DSaLTaHSg33643+I0tf2GUx6uDmzI2bMdqDWwUWW3lhqlTxOrnO1wViDuEIDj1e7wo1HN7ttGGtgI1WrBEaesMesOFkjkCiYAC9C6z1J8XYt4nZ6DKwt58+iAEwqXgVABGLH0cKLJbCSPAEFRTcxmlpeIp9lqMygjYA7LOAKwEtCN4xwMwWUm2BxOJSN6meEBAA

Related Issues:

Perhaps this a design limitation per the following PR?

#33622
#33622 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions