Skip to content

Incorrect inference when using an optional argument Β #57021

Closed as not planned
@ShayDavidson

Description

@ShayDavidson

πŸ”Ž Search Terms

Inference, Return, Arguments, Parentheses, Identity Function.

πŸ•— Version & Regression Information

This reproduces in all available playground versions (tried down to 3.3.3), and also in 5.3.3.

⏯ Playground Link

Link

πŸ’» Code

This is a followup on #49951 which @Andarist asked me to open a follow-up issue. Also relates to #47599

Probably better to check the playground for code examples, but here's the TL;DR:

TYPES DECLERATIONS:

type Schema = Record<string, unknown> // modified from original for the sake of the example, if it doesn't make sense

type StepFunction<
  TSchema extends Schema = Schema,
> = (anything: unknown) => {
  readonly schema: TSchema
  readonly toAnswers?: (keys: keyof TSchema) => unknown
}

function step<TSchema extends Schema = Schema>(
    stepVal: StepFunction<TSchema>,
  ): StepFunction<TSchema> {
    return stepVal
  }

EXAMPLES:
Notice the returned object of all functions is the same! The difference is in whether we have the argument for the step function or not. Note that if I do Parameters<typeof myStepValue> even when the argument is missing, it's inferred correctly (!)

// WORKS: `keys` is inferred based on the `schema`
// - no argument for `step` function
// - no `return` keyword
const workingExample = step(() => ({
  schema: {
    attribute: 'anything',
  },
  toAnswers: keys => {
    // RESULT: `keys` inferred successfully as `attribute`
    type Test = string extends typeof keys ? never : 'true'
    const test: Test = 'true'
    return { test }
  },
}))
// FAILS: `keys` is not inferred based on the `schema`
// - has argument for `step` function
const nonWorkingA = step(_something => ({
  schema: {
    attribute: 'anything',
  },
  toAnswers: keys => {
    // RESULT: `keys` failed to be inferred hence defaults to `string`
    type Test = string extends typeof keys ? never : 'true'
    const test: Test = 'true'
    return { test }
  },
}))

πŸ™ Actual behavior

Nested value's function argument cannot be inferred correctly.

If I change the property (toAnswers) from a function to a simple property, there are no inference issues.

πŸ™‚ Expected behavior

Nested value function argument should be inferred correctly regardless of the return keyword or declaring the arguments.

Additional information about the issue

Like mentioned above, this is a followup on #49951 and #47599

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