TypeScript · Senior · Question 34 of 75

When is the double assertion x as unknown as T justified?

Explanation

A plain as is forbidden between unrelated types; via unknown you can assert anything - and be wrong. If you can't avoid it (e.g. in a low-level utility), hide it inside a function with a runtime check and tests. For JSON, validate with a schema.

Further reading

Problem with a question

TypeScript · Senior · question 34

Test yourself

Take the TypeScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz