๐Ÿ›ก๏ธ TS Basic Types

TypeScript by Definition

TypeScript is an open-source programming language. It is a strict syntactical superset of the language we love, JavaScript! TypeScript allows us to add optional static typing into our loosely typed JavaScript to create typed JavaScript.

Supersets

In programming, a superset (TypeScript) is a language that contains all features of the language extended from (JavaScript), and has been extended or enhanced to include additional capabilities or features. Any sound code from the extended language (JavaScript) is also sound superset code (TypeScript).

JS VS TS

Before we continue, a few important points to clear up any confusion.

  • TypeScript does not replace JavaScript in the world of web development.
    • JavaScript is still the scripting language of the web used to create interactivity for users.
  • TypeScript is compiled into JavaScript.
    • In this context: code written in one language output in another language.
  • JavaScript is transpiled for browsers.
    • In this context: a source file converted to a different version of the same language.

Basic Types

TypeScript supports the same types as JavaScript, plus one more enumeration type. On a side note, JavaScript does not support Enums natively, but outside TypeScript can be created using Object.freeze on a previously created object, locking / freezing all enumerable properties on it, where no new enums can be added.

Before jumping into the types in TypeScript, lets quickly remind ourselves on the 8 basic JavaScript data types:

  • number (integer or floating-point, atom, primitive)
  • bigint (integer numbers with arbitrary length, atom, primitive)
  • string (0+ chars, atom, primitive)
  • boolean (true/false, atom, primitive)
  • null (unknown values, atom)
  • undefined (unassigned values, atom, primitive)
  • object (data structures, molecule of atoms)
  • symbol (unique identifiers, primitive)

All the primitive values above also have object equivalents that wrap around them, where each primitive wrappers valueOf() method returns the primitive value (String, Number, BigInt, Boolean, Symbol). Check out my ๐Ÿงต Strings Cheat Sheet for an example on JavaScripts automatic conversion of primitive types.

Boolean

Basic data type with true/false value.

1let loading: boolean = false;
2
3 // Changing from boolean type
4 loading = 'Loading...';
5 // Should error: Type 'string' is not assignable to type 'boolean'

Number

Similar to JavaScript, TypeScript numbers are one of:

  • number (integer or floating-point)
  • bigint (integer numbers with arbitrary length)
1let number: number = 10;
2 let pi: number = 3.14159265359;
3 let bigInt: bigint = 100n;
4
5 // Changing from number type
6 number = 'Number';
7 // Should error: Type 'string' is not assignable to type 'number'

String

Similar to JavaScript, Strings are represented with single or double quotes.

1let fruit: string = 'lemon ๐Ÿ‹'; // single
2 fruit = "mango ๐Ÿฅญ" // double
3 let favourite = `My favourite fruit is: ${fruit}` // or template literal
4
5 // Changing from string type
6 fruit = true
7 // Should error: Type 'string' is not assignable to type 'boolean'

Array

Array types can be defined two ways:

  • The type of the elements inside the array followed by self closing array brackets to denote the type of elements inside the array []
  • Using a generic array type, like so: Array<elemType>

Note: PrimitiveType[] is the same as using generic syntax Array<PrimitiveType>, it's just shorthand syntax for defining an array of types.

1let fruits: string[] = ['๐Ÿ‹', '๐Ÿฅญ', '๐Ÿ‘', '๐Ÿ', '๐Ÿฅ', '๐Ÿ“'];
2let fruitsGenericType: Array<number> = ['๐Ÿ‹', '๐Ÿฅญ', '๐Ÿ‘', '๐Ÿ', '๐Ÿฅ', '๐Ÿ“'];
3
4// Changing either array type
5
6fruits = true;
7fruitsGenericType = true;
8
9// Should error: Type 'boolean' is not assignable to type 'string[]'
10
11// Trying to use array methods will also error when compiling
12// ... for example adding a new item with different type
13
14fruits.push(100);
15
16// Should error: Argument of type 'number' is not assignable to parameter of type 'string'

Tuple

We can use Tuples to help define arrays with fixed element types. Previously we looked at defining array types that consisted of elements of the same type. With a tuple, we can represent an array of values with different types.

1let tuple: [string, string, number, boolean, number, string];
2tuple = ['๐Ÿ‹', '๐ŸŠ', 5, true, 10, '๐Ÿ…'];
3/* [0] [4] */
4
5// Changing any item type in the tuple
6tuple = [false, '๐ŸŠ', 5, true, '๐Ÿ‹', '๐Ÿ…'];
7/* [0] [4] */
8
9/*
10Index [0] should error
11 - Type 'boolean' is not assignable to type 'string
12 ... a whale emoji is not a boolean, it's a string!
13Index [4] should error
14 - Type 'string' is not assignable to type 'number'
15 ... the value 10 is not a whale emoji, it's an integer!
16*/
17
18// Trying to access an element outside the set
19console.log(tuple[6]);
20
21/*
22Should error
23 - Tuple type '[string, string, number, boolean, number, string]' of length '6' has no element at index '6'
24*/

Enum

An enum allows us to give sets of numeric values nicer names, which can be nice to add context around your logic. With enums, we may have a value returned from some logic but we don't know what enum the value maps to, in this scenario we can just lookup the enum member, see below.

1enum Step {
2 LOGIN,
3 RESET_PASSWORD,
4 CREATE_ACCOUNT,
5 }
6
7 let userStep = Step.RESET_PASSWORD;
8
9 console.log(userStep); // 1
10
11 // Looking up the enum member:
12 console.log(Step[2]); // CREATE_ACCOUNT

Unknown

On occasion we might not know what the type for a variable should be. This could be from dynamic content, For example from an external api. We should inform any future developers and of course the compiler that this value could be anything. In this scenario, we should use the unknown type and where suitable add conditional typeof checks.

1// Imagine this is some async external call...
2const returnRandomItem = (): unknown => {
3 const types = [true, '๐Ÿ™', 123, '๐Ÿ '];
4 const randomLookup = Math.floor(Math.random() * 4);
5 return types[randomLookup];
6};
7
8let value: unknown = returnRandomItem();
9// could return string on this call '๐Ÿ™'
10
11value = returnRandomItem();
12// could return true on this call
13value = returnRandomItem();
14// could return string on this call '๐Ÿ '
15value = returnRandomItem();
16// could return number on this call 123
17
18if (typeof value === 'string') {
19 console.log('we got a string', value);
20}
21
22if (value === true) {
23 console.log('we got a true boolean', value);
24}
25
26if (typeof value === 'number') {
27 console.log('we got a number', value);
28}
29
30// Another example
31let anything: unknown = 4;
32anything = '๐Ÿ”ฅ';
33anything = 1;
34anything = false;
35anything = ['๐Ÿ”ฅ', '๐Ÿ”ฅ', '๐Ÿ”ฅ'];

Any

You will likely encounter a scenario where you want to opt out of type checking or just want the compiler to stop shouting 'error' at you. We can use the 'any' type to opt out, which will tell our compiler to ignore/turn off type checking for this thing (value or function). Some reasons for this could be:

  • You are in mid-development of a new feature (focused on getting the logic behind your code working first), debugging, migrating pieces of a JavaScript project over to use TypeScript, or just testing a new idea/potential fix and not something you are ready to land or have reviewed.
  • Not all type information is readily available to you, so it makes sense to opt out for now.
  • A 3rd party library or external dependency has no TypeScript support. Declaring all the types here could be a substantial effort.

Using 'any' is neat for opting in and out of type checking, but in turn, defeats the purpose of using TypeScript. We lose type safety, which is the main benefit of the language. I think it goes without saying, try and avoid using the any type if possible.

1import { alienUtilityFunction } from 'someThirdPartyLib';
2
3 /* 3rd party utility may not be using TypeScript
4 ... and it would be a massive effort to type it
5 ... so we just use any type
6 */
7 let alien: any = alienUtilityFunction('๐Ÿšถ', '๐Ÿ›ธ');
8
9 console.log(alien) // '๐Ÿ‘ฝ'
10
11
12 /* --------------------------------------------------------------- */
13
14
15 // looselyTyped, skipped by compiler
16 let anyExample: any = {};
17
18 /* Compiler doesn't check this
19 ... even though it might not exist
20 */
21 let anyValue = anyExample.someFunctionProperty();
22
23 /* Which may crash your app if it doesn't exist at run time )=
24 ... Uncaught TypeError: anyExample.someFunctionProperty is not a function
25 */
26
27
28 /* --------------------------------------------------------------- */
29
30
31 // strictly typed, NOT skipped by compiler
32 let unknownExample: unknown = {};
33
34 /* Compiler check this
35 ... Object is of type 'unknown'
36 */
37 let unknownValue = unknownExample.someFunctionProperty();

Void

You should use void for a function that performs an operation without returning a value.

1const logEmojis = (emojis: string[]): void => {
2 console.log(...emojis); // ๐Ÿ‚ ๐ŸŒ๏ธ ๐ŸŠโ€โ™‚๏ธ โ›น๏ธโ€โ™€๏ธ ๐Ÿ‹๏ธโ€โ™‚๏ธ ๐Ÿ„โ€โ™€๏ธ
3 };
4
5logEmojis(['๐Ÿ‚', '๐ŸŒ๏ธ', '๐ŸŠโ€โ™‚๏ธ', 'โ›น๏ธโ€โ™€๏ธ', '๐Ÿ‹๏ธโ€โ™‚๏ธ', '๐Ÿ„โ€โ™€๏ธ']);

Was this useful?

Thanks for reading! Time for one more?

while (!valid) {
await askDirectoryName({ ui })
.then(val => { valid = true; dir = val })
}

๐Ÿš€ Productive Tooling

19 Mar 2021 โ€ข ๐Ÿ“– 10 min read โ€ข Updated 15 Mar 2026
โ˜• Coffee needed

Increasing my productivity with custom tooling.

0
0
0
JAVASCRIPT NODE
'The Joe Codes'.split(' ') // ['The', 'Joe', 'Codes']
'The Joe Codes'.includes('Joe') // true

๐Ÿงต Strings Cheat Sheet

30 Dec 2020 โ€ข ๐Ÿ“– 10 min read โ€ข Updated 15 Mar 2026
๐Ÿ”ฐ Beginner friendly

Cheat sheet to help you master working with JS strings.

0
0
0
JAVASCRIPT