This page looks best with JavaScript enabled

Type casting in Typescript

 ·   ·  ☕ 5 min read

“Typecast types in Typescript” : that’s three “types” in a sentence with three significant words, and for that, I should tap out (but I don’t).

We see a lot about “type assertions” in to type conversations (or conversions!) in Typescript. Type assertions enable you to override default type inference for neutral types. We have discussed about type assertion before.

Typecasting refers to type conversions. While they don’t function similar to other strongly typed languages, they do exist.

We will see more of type assertions and casting after this preface.

Types, you say?

For a basic introduction of “types” - head over to types in Typescript and Javascript types.

Typescript supports -

  • built-in types (basic e.g. number, string, boolean,and special types e.g. any, unknown)
  • additional types (e.g. collections like enum and even user-defined types)

You define variables with types -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
let decimal: number = 1;
let color: string = "indigo";

// anything, really
let notSure: any = "abc";

// collections
let list: number[] = [1, 2, 3];

enum Color {
  Red,
  Green,
  Blue,
}
let c: Color = Color.Green;

It’s all a good world with types until it isn’t. It so happens that -

  • you (think you) know more than what the compiler knows. You want to tell compiler that a variable is of a specific type.
  • values may need to be moved across types in the course of doing something

Type Assertions and Typecasting

The process of changing types is what is called “type casting”. Typecasting in strongly typed languages like C# allow us to convert types.

1
2
3
4
string numStr = "123";
int numNum;

bool isParsable = Int32.TryParse(numStr, out numNum);

The code checks whether a given string is a valid number and outputs the number. The “string” or “number” types are treated in a consistent way by both the compiler and runtime engine.

Typescript behaves differently. It is compiled to Javascript, which does not give two hoots about your defined types, and there is no “runtime” to enforce types during execution. All Typescript can do is to apply all its smarts during compilation of Typescript to Javascript code.

Type assertions let the Typescript compiler know that a given variable should be treated as belonging to a certain type. There are no “exceptions” or data restructuring associated with assertions, except minimal validations (we refer this behaviour as “validations that are applied statically”).

But, implicit types do exist during program execution, and type conversion behaves similar to Javascript since the execution engine is, well, Javascript. But, you need to make explicit conversions in Typescript to humour the compiler, and probably, everyone else in your team.

Aside: IMO it is more fun to use implicit conversions that reduce code, confuse people and make it hard to write tests.

When & where to use type casting and type assertion?

Type assertions helps you to force types when you are not in control of them. For e.g. -

  1. you are processing user data (with unreliable types)
  2. working with data that has changed shape over years (employee code was numeric, now it is alphanumeric :))
  3. receiving data from an external program

Consider this example that uses any, a special type that represents any type in Typescript. You convert any to a specific type to process it further -

1
2
3
let whatanum: any = 42;
whatanum = "is this the answer to everything?";
whatanum = true;

We can start with any and use type assertion to denote that the variable is in fact a number.

1
2
3
let whatNum: any = 42;
let reallyNum = <number>whatNum;
console.log(typeof reallyNum); // number

Or, consider this example with unknown, another special type in Typescript -

1
2
3
4
5
const clueless: unknown = "1";
const clueNum: number = <number>clueless;

// another format
const clueNumPreferred = clueless as number;

The compiler does not know better about any or unknown variables to process further - so we make the compiler “see” the variables for what they really are.

Typecasting, on the other hand, helps you to convert types and provide consistent (expected) results :). For e.g. -

  1. concatenation of a number and string
  2. convert arrays of numbers to strings for formatting and display

How do I assert types?

There are two ways to do type assertions.

  1. Bracket syntax. e.g. let length: number = (<string>lengthField);
  2. Use as. e.g. let length: number = (lengthField as string);

There is no difference between the two ways and the end result is always the same. Note that if you are using JSX you have to use as syntax.

Type conversion in Typescript

Converting specific types is similar to Javascript.

From _ to String

We convert any type to string by using String(x) or x.toString.

1
2
3
4
5
console.log(String(42)); //"42"
console.log(typeof String(42)); // "string"

console.log(String(true)); //"true"
console.log(String(undefined)); //"undefined"

From _ to Number

This is so radically different from string.

1
2
3
Number("0"); // 0
Number("abc"); //NaN
Number(true); // 1

There are additional helper functions that, well, help you do strange things -

1
2
parseInt("42life"); //42
parseFloat("3.14pi"); //3.14

From _ to Boolean

Convert “stuff” to boolean.

1
2
Boolean("a"); // true
Boolean(null); // false

From object to array

Yes, you read that right - let’s see an example of converting object to array in style. Not quite a glaring example of “type conversions”, but apparently, people stare in awe at such code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
const planets: Object = {
  mercury: { name: "Mercury", position: 1 },
  venus: { name: "Venus", position: 2 },
  earth: { name: "Earth", position: 3 },
};
const planetsArr: Array<Object> = Object.keys(planets).map(
  (key: string): string => planets[key]
);
console.log("planetsArr", planetsArr);

/* 
output:
[
  { name: "Mercury", position: 1 },
  { name: "Venus", position: 2 },
  { name: "Earth", position: 3 },
]
*/

The End

We saw type assertions, typecasting and examples of type conversions. Hopefully that has confused you a bit more about the wonderful world of types.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things