Skip to content

Inferred return type of functions in array allows incorrect value for optional property of return typeΒ #62167

@ulrichstark

Description

@ulrichstark

πŸ”Ž Search Terms

infer return type function array property optional

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about "return", "property", "properties", "infer"

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.9.0-beta#code/JYOwLgpgTgZghgYwgAgGLAB7IN4ChnIC2EAziXAOYQD8AXMiWFKBQNy4C+uuYAngA4oAwgAsICANbIAvMgAUAShkA+NJna4EAexCNkCMZJIBGeqPESA2gF0ZyS-nlLpqudg4KANI8Ur52IlJyKnoAVnDkD09kAHoY5AA5AHlkAFEAJXSk9NxrDTjkCAx+ABtgBGAwZCgIMABXKBBkPkFNHT0DCxIAJjNDK1tZBwJfF38onwV6dCwxt0CySggwiKjY+IAVARQAchA6wgAjaB3kYBJkEC0quDJgChA4Q5KUMC1m7eQdxmYQCh3cvl4gB3SoiZAAIlu+naYAhbV0VU6RgAzH0LDY7MMnH43BMRs5XAFiIsQshwqFIl51sgtoIvvsjiczhcrjc7g8ni9mu8WrsfiwAbZodpEUDkKCwCItHUqjBgFA9JUIIQER1+iQACzoySYoaTXHEoJLFaUtYFOm7RnHKCnc6Xa7IW4ke6PZ6vXmfb5MQWA3BAA

πŸ’» Code

interface Fix {
  message?: string;
}

type Check = () => Fix;

const checks: Check[] = [
  () => ({}),
  () => ({ message: 555 }), // no error reported
];

πŸ™ Actual behavior

No error is reported on the last item of the array.

πŸ™‚ Expected behavior

It should report an error, because number 555 is not a legal value for optional property message of type string.

Additional information about the issue

Workaround 1: add explicit return type

const checks: Check[] = [
  () => ({}),
  (): Fix => ({ message: 555 }), // Type 'number' is not assignable to type 'string'
];

Workaround 2: add "as const"

const checks: Check[] = [
  () => ({}),
  () => ({ message: 555 }), // Type 'number' is not assignable to type 'string'
] as const;

Workaround 3: remove first item

const checks: Check[] = [
  () => ({ message: 555 }), // Type 'number' is not assignable to type 'string'
];

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