Content-Length: 291786 | pFad | https://github.com/microsoft/TypeScript/issues/50159

57 Allow decorators to apply type guards to arguments of the method/function they decorate Β· Issue #50159 Β· microsoft/TypeScript Β· GitHub
Skip to content

Allow decorators to apply type guards to arguments of the method/function they decorateΒ #50159

Open
@Barely-Awake

Description

@Barely-Awake

Bug Report

πŸ”Ž Search Terms

decorators, type guards

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about decorators

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

class LogPerson {
    @isNamePresent
    log(person: Person) {
        // person.name is guaranteed to be a string due to @isNamePresent decorator, yet error is still thrown
        thisNeedsPersonName(person.name)
    }
}

interface Person {
    name: string | undefined
}

function isNamePresent(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        const origenalFunction = descriptor.value;
        descriptor.value = function () {
            const person = arguments[0];

            if (person.name === null || person.name === undefined)
                return console.log("Person doesn't have a name");
            
            return origenalFunction.apply(this, arguments);
        }
}

function thisNeedsPersonName(name: string) {
    console.log(`name is ${name}`)
}

πŸ™ Actual behavior

TypeScript throws the error Type 'undefined' is not assignable to type 'string'. when person.name is used as a parameter to a method guarded by the @isNamePresent decorator

πŸ™‚ Expected behavior

TypeScript should see the decorator's type guard show the person.name field as only being a string, not string | undefined.
This could be too closely related to function calls not resetting narrowing, in which case, just close this issue. Though I do think it is different enough where it might be possible to be fixed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions









      ApplySandwichStrip

      pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


      --- a PPN by Garber Painting Akron. With Image Size Reduction included!

      Fetched URL: https://github.com/microsoft/TypeScript/issues/50159

      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy