Emmanuel Akinfulubi

TypeScriptAdvanced types

any vs unknown with type assertions in TypeScript

7 Casting an any to text

easy

Declare a value as any, then use an assertion to treat it as text. Then show why unknown is the better starting point.

Stuck? Three hints, smallest first
  1. 1. value as string is the assertion. There is also the older <string>value form; avoid it, since it clashes with JSX.
  2. 2. any switches checking off completely. unknown keeps it on and forces you to prove things.
  3. 3. An assertion has no runtime effect. If the value was not really text, the failure happens later and somewhere else.

The answer, and proof it works

const same = (a: unknown, b: unknown): boolean =>
  JSON.stringify(a) === JSON.stringify(b);

function test(name: string, got: unknown, want: unknown): void {
  console.log(
    (same(got, want) ? 'ok   ' : 'FAIL ') + name +
    (same(got, want) ? '' : `  got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
  );
}

let loose: any = 'a string in disguise';
const asText = loose as string;

console.log('length via assertion:', asText.length);

// Why any is dangerous: this compiles, and it is a lie.
const lie: any = 42;
const pretend = lie as string;
// pretend.toUpperCase() would throw at runtime. Nothing warned us.
const brokeAtRuntime = typeof pretend === 'string';

// unknown is the safe version of the same idea.
const safer: unknown = 'also a string';
// safer.length would be an error: 'safer' is of type 'unknown'.
const checked = typeof safer === 'string' ? safer.length : 0;

console.log('any let a number pose as text:', brokeAtRuntime);
console.log('unknown forced a check, length:', checked);

test('assertion gave us the length', asText.length, 20);
test('the assertion on a number was a lie', brokeAtRuntime, false);
test('unknown plus a check is honest', checked, 13);

Output


      

as is a promise, not a conversion. The second block shows the cost: lie as string compiles, and typeof pretend === 'string' is false at runtime, which proves the compiler was told something untrue. Start from unknown and the compiler makes you prove it instead.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.