Happylab Logo
Published on

Day07: Learning TypeScript - Primitive Types

Authors

Day07: Learning TypeScript - Primitive Types


string

Define a string type using string:

const myName: string = 'iris'
const myAge: number = 18

const sentence: string = `Hello, my name is ${myName}.
I'll be ${myAge + 1} years old next month.`

number

Define a number type using number:

const decLiteral: number = 6
const notANumber: number = NaN
const infinityNumber: number = Infinity

boolean

Define a boolean type using boolean:

const isDone: boolean = false

null & undefined

In JavaScript, null is a value that has been assigned but is empty. undefined is a declared variable that has not been assigned a value.

In TypeScript, the use of these two values depends on whether strict null checks are set in tsconfig. The default for strict null checks is false.

However, if "strict": true is enabled (which is the default), all strict type-checking options are activated, including strict null checks.

For how to generate and set up tsconfig, please refer to day05.

strictNullChecks off

First, we set strictNullChecks to false, allowing assignment of null or undefined to other types.

null:

const n: null = null
// For example: assign to string type
const city: string = n
console.log('city', city)

undefined:

const u: undefined = undefined
// For example: assign to number type
const price: number = u
console.log('price', price)

strictNullChecks on

At this point, we will see an error in the file: Type 'null' is not assignable to type 'string'. Under strict checks, you cannot assign to other types.

Error

What to do if there's an error?

If we want to achieve the effect of false under strict checking, we need to use Union Types to allow values to have multiple types.

const n2: null = null
const city2: string | null = n2 // can be string or null
const city3: string | null = 'taipei'

const u2: undefined = undefined
const price2: number | undefined = u2 // can be number or undefined
const price3: number | undefined = 100

Yay! Primitive Types are done. I didn't expect to write so much about null & undefined. Union Types will be introduced in detail later. Next, let's look at Object Types!


References

https://willh.gitbook.io/typescript-tutorial/basics/primitive-data-types https://www.typescriptlang.org/docs/handbook/2/everyday-types.html https://www.typescriptlang.org/zh/tsconfig#strictNullChecks