Skip to content

Generic return type of function is enforced inconsistently in some casesΒ #51706

Closed

Description

Bug Report

πŸ”Ž Search Terms

  • record generic
  • explicit return with generics

πŸ•— Version & Regression Information

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

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

const genericWithRecordReturnType = <T extends any>(arr:Array<T>):Record<number,T> =>{
    return {
        definitelynotanumber:arr[0]
    };
};

const genericWithRecordReturnTypeThatWorks = <T extends any>(arr:Array<T>):Record<number,T> =>({
    definitelynotanumber:arr[0]
});

function test<T>(arr:Array<T>):Record<number,T>{
    return{
    definitelynotanumber:arr[0]
}
}

πŸ™ Actual behavior

I receive no errors for the function definition for the function that explicitly returns the record infered in the assigmnet above but I do for returns without interum assignment

πŸ™‚ Expected behavior

I should receive errors for both cases or the behaviour should atleast be consistant

Activity

  1. fatcerberus commented on Dec 1, 2022

    @fatcerberus

    The error is detected by excess property check, which only works for directly assigned object literals. Outside of that, the object with a non-number property is otherwise assignable to the numeric record. See #48906.

  2. NICHTJ3 commented on Dec 1, 2022

    @NICHTJ3
    Author

    Pretty similar to #51680 and #48906. If you guys are okay with it I might close as a duplicate? πŸ€”

  3. fatcerberus commented on Dec 1, 2022

    @fatcerberus

    Yeah, sorry I wasn’t clear above - this is working as intended. Objects can have more properties than their type requires, the compiler just does an excess property check in certain cases as a kind of basic sanity check but you shouldn’t rely on it to enforce runtime safety.

  4. locked as resolved and limited conversation to collaborators on Oct 22, 2025
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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions