Skip to content
tsCheatSheet
GitHub

Casting

Casting Types

Casting overrides the variable type, which you may want to do when you know more about the type than the compiler does.

Casting using as

let a: unknown = 'Hello World!';

console.log(a.length);
// Property 'length' does not exist on type 'unknown'.
console.log((a as string).length); // Works because now
// the compiler sees it as a string.

An example that might make more sense.

let a: unknown = 'Hello World!';

function unknownCastToString() {
	let aAsString = a as string;
	console.log(a.length); // returns error TS2339: Property
	// 'length' does not exist on type 'unknown' because
	// .length doesn't exist on unknown.
	console.log(aAsString.length); // returns 12 because we've
	// cast a to string, so .length method works
}

unknownCastToString(); // function call

Casting doesn’t really change type, it tells the compiler to treat it as a different type.

let a: unknown = 3;

console.log((a as string).length); // logs undefined
// because numbers don't have a length.

TypeScript Typechecks Casts

console.log((3 as string).length); // Error: Conversion
// of type 'number' to type 'string' may be a mistake
// because neither type sufficiently overlaps with the
// other. If this was intentional, convert the expression
// to 'unknown' first.

Casting using <>

Note: doesn’t work in TSX.

let a: unknown = 'Hello World!';

console.log((<string>a).length); // Works.

Forced casting

You can force cast to any type by casting to unknown, then to the type you want. This will override any errors thrown by casting.

let a = 'Hello World!';
// prettier-ignore
console.log(((a as unknown) as number).length); // a is not
// really a number so returns undefined.