Any and unknown conditionals
Concept and syntax
Special types behave differently in conditional comparisons. For this string test, any produces both branch results while unknown selects the false branch. Do not interpret any as a precise universal proof; test edge cases explicitly.
Working example
Save each snippet separately as main.ts in a fresh directory with TypeScript 5.8.3. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts and run accepted snippets with node main.js. Type aliases are erased; assignments and diagnostic checks demonstrate the type relations, not the printed output alone.
type Kind<T>=T extends string?"text":"other";const a:Kind<any>="text"; const b:Kind<any>="other"; const c:Kind<unknown>="other"; console.log(a,b,c);Expected output:
text other otherCommon mistake
Intentionally invalid; compile separately and do not execute.
type Kind<T>=T extends string?"text":"other";const c:Kind<unknown>="text";Expected diagnostic: TS2322. unknown is not assignable to string without refinement, so only other is allowed.
Independent comparison
The false branch is also available for any in this test. Expected: 'other other\n'
type K<T>=T extends string?"text":"other"; const x:K<any>="other"; const y:K<unknown>="other"; console.log(x,y);Practice and recap
Compare Kind<never> and Kind<string | number>.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Any and unknown conditionals — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Any and unknown conditionals is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Kind<T>=T extends string?"text":"other";const a:Kind<any>="text"; const b:Kind<any>="other"; const c:Kind<unknown>="other"; console.log(a,b,c);Which diagnostic and explanation match the rejected example under the lesson settings?
type Kind<T>=T extends string?"text":"other";const c:Kind<unknown>="text";What is Kind<string | number>?