Like any, unknown represents any value, but we can’t operate on unknown type until we refine it by checking what it is with typeof or instanceof.
Like boolean, unknown only supports comparison operations(==, ===, ||, &&, ?) and negation operation(!).
let a: unknown = 10; //unknown
let b = a === 123; // boolean
let c = a + 10; // Error TS2571: Object is of type 'unknown'
if (typeof a === 'number') {
let d = a + 10; // number
}
- Typescript will never infer something as
unknown, we have to explicitly annotate it (a). unknownsupports comparison operations and negation operation, same asbooleandoes(b).- we can’t do things that assume an
unknownvalue is of a specific type(c). - We can operate on
unknowntype after checking it withtypeoforinstanceof.