Microsoft/TypeScript

Types that depend on constants are not narrowing correctly

Open

#56.417 geöffnet am 15. Nov. 2023

Auf GitHub ansehen
 (10 Kommentare) (0 Reaktionen) (0 zugewiesene Personen)TypeScript (6.726 Forks)batch import
BugDomain: Conditional TypesHelp Wanted

Repository-Metriken

Stars
 (48.455 Stars)
PR-Merge-Metriken
 (Durchschn. Merge 6T 17h) (9 gemergte PRs in 30 T)

Beschreibung

🔎 Search Terms

"ternary narrowing", "ternary constant", "constant narrowing", "constant dependent"

🕗 Version & Regression Information

  • This is the behavior in every version I tried (including nightly), and I reviewed the FAQ.

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.2.2#code/MYewdgzgLgBAQgeQQGRgXhlATgVwKYwCGEMokUAUBVAJ4AOBAKgPqO4EYDeMAHgFwxoWAJZgA5gBoYjAUNFiYAX2r0mzAGKEANhA4xu-QdnlT1s4+KVVaDaehgAKG3hAAzeEmQBKGHh5Q8MAATEmx8GAB+aVZ2GAEWTR08KgpXHDBgKGFwGFcHL3j9ChgS0nBoGAA3QiwZaLZwrl4BAHJq2papOpaxEBAglqtSsvIqmrNoxN17A1b29U6YCZaQAGtCGkHlYtKsPCgcLDAPFEix2rjz9QpFIA

💻 Code

const BOOL = true as const

type T_True = { x: string, T: string }
type T_False = { x: string, F: string }

type T = (typeof BOOL) extends true ? T_True : T_False

function f(): T {
    const varT: T_True = { x: 'varT', T: 'good' }
    const varF: T_False = { x: 'varF', F: 'okay' }

    return BOOL ? varT : varF
}

🙁 Actual behavior

Typechecking fails with the error Type 'T_True | T_False' is not assignable to type 'T_True'. Property 'T' is missing in type 'T_False' but required in type 'T_True'. on the return statement.

🙂 Expected behavior

Typechecking should pass, since the const BOOL = true as const should mark the false ternary case as unreachable.

I also tried making T generic with respect to BOOL, and splitting the ternary operator into an if/else, but the same error persisted regardless.

Additional information about the issue

No response

Contributor Guide