Microsoft/TypeScript

Computed type key inference inconsistent with identical explicitly declared type

Open

#59,987 opened on Sep 17, 2024

View on GitHub
 (2 comments) (1 reaction) (0 assignees)TypeScript (6,726 forks)batch import
BugDomain: Mapped TypesHelp Wanted

Repository metrics

Stars
 (48,455 stars)
PR merge metrics
 (Avg merge 6d 17h) (9 merged PRs in 30d)

Description

🔎 Search Terms

keyof required keys key evaluation reduce getReducedType

🕗 Version & Regression Information

  • This is the behavior in every version I tried

⏯ Playground Link

https://tsplay.dev/WKQkzN

💻 Code

type distilled = distill<{
	//   ^?
	foo: "default"
	bar?: number
}>

// incorrectly inferred as unknown
type requiredDistilledKey = requiredKeyOf<distilled>
//   ^?

// explicit declaration identical to hover of distilled
type declared = {
	bar?: number
} & {
	foo?: "default"
}

// now correctly inferred as never
type requiredDeclaredKey = requiredKeyOf<declared>
//   ^?

type requiredKeyOf<o> = {
	[k in keyof o]-?: o extends { [_ in k]-?: o[k] } ? k : never
}[keyof o]

type distill<t> = t extends object ? distillMappable<t> : t

type distillMappable<o> = {
	[k in keyof o as k extends inferredDefaultKeyOf<o> ? never : k]: distill<o[k]>
} & {
	[k in inferredDefaultKeyOf<o>]?: distill<o[k]>
}

type inferredDefaultKeyOf<o> = {
	[k in keyof o]: o[k] extends "default" ? k : never
}[keyof o]


🙁 Actual behavior

requiredDistilledKey inferred as unknown

🙂 Expected behavior

requiredDistilledKey inferred as never, consistent with the equivalent declared version

Additional information about the issue

No response

Contributor guide