본문 바로가기
Web/JavaScript

[TypeScript] Basic Types

by llHoYall 2021. 7. 4.

TypeScript gives us some data types and it helps us a lot.

Boolean

It has a true/false value.

let isSuccess: boolean = true;

Number

let binary: number = 0b0111;
let octal: number = 0o765;
let decimal: number = 7;
let hex: number = 0xcafe;
let big: bigint = 1234n;

If you want to use bigint, you need to use ES2020 or later.

String

let familyName: string = 'kim'
let givenName: string = "hoya"
let myName: string = `${familyName}, ${givenName}`

You can use single quotes(') and double quotes("), and you can also use backquote(`) with template strings.

Array

There are two ways to denote Array.

let numArray: number[] = [1, 2, 3];
let fruit: Array<string> = ["apple", "banana", "coconut"];

Tuple

Tuple can contain various types of values, while Array can only contain the same type of values.

let tuple: [string, number];
tuple = ['kim', 18];

console.log(`${tuple[0]}, ${tuple[1]}`)
// kim, 18

Enum

Enum assigns a value starting with zero and increasing by one to the element.

enum Color {
  RED,
  GREEN,
  BLUE
}
let r: Color = Color.RED;
let g: Color = Color.GREEN;
let b: Color = Color.BLUE;

console.log(`${r}, ${g}, ${b}`);
// 0, 1, 2

You can set the starting number.

enum Color {
  RED = 3,
  GREEN,
  BLUE
}
let r: Color = Color.RED;
let g: Color = Color.GREEN;
let b: Color = Color.BLUE;

console.log(`${r}, ${g}, ${b}`);
// 3, 4, 5

Of course, you can set the value to all the elements.

enum Color {
  RED = 1,
  GREEN = 3,
  BLUE = 5
}
let r: Color = Color.RED;
let g: Color = Color.GREEN;
let b: Color = Color.BLUE;

console.log(`${r}, ${g}, ${b}`);
// 1, 3, 5

Enum can have other types like string.

enum Color {
  RED = 'red',
  GREEN = 'green',
  BLUE = 'blue'
}
let r: Color = Color.RED;
let g: Color = Color.GREEN;
let b: Color = Color.BLUE;

console.log(`${r}, ${g}, ${b}`);
// red, green, blue

 

But, Enum type doesn't strict, so you need to use the union type if possible.

enum Color {
  RED,
  GREEN,
  BLUE
}
let color: Color = Color.RED;
color = 7;
console.log(color)
// 7

type AvailableColors = 'RED' | 'GREEN' | 'BLUE';
let myColor: AvailableColors = 'RED'
myColor = 'YELLOW'  // Error: Not assignable

Unknown

let unknownVar: unknown = 4;
console.log(unknownVar)
// 4

unknownVar = "hello";
console.log(unknownVar)
// hello

unknownVar = false;
console.log(unknownVar)
// false

Unknown type allows for any type of values.

Therefore, you have to carefully use it.

Any

Unlike unknown, variables of type any allow you to access arbitrary properties, even ones that don't exist.

These properties include functions and TypeScript will not check their existence or type.

let anyVar: any = {};

Any type is recommended for temporary use only during development.

You need to gradually change to using a specific type during development.

The type system is a strong point of TypeScipt.

Therefore, there is no reason to use TypeScript if you overissue any type.

Void

Void is a little like the opposite of any, i.e., the absence of having any type at all.

let unusable: void;
unusable = undefined;

Null and Undefined

By default null and undefined are subtypes of all other types.

That means you can assign null and undefined to something like number.

However, it depends on the configuration.

let undefVar: undefined = undefined;
let nullVar: null = null;

Never

The never type represents the type of values that never occur.

For instance, never is the return type for a function expression or an arrow function expression that always throws an exception or one that never returns.

Any isn't assignable to never.

function error(message: string): never {
  throw new Error(message);
}

const infiniteLoop = (): never => {
  while (true) {}
}

Object

Object is a type that represents the non-primitive type.

It has written "Generally, You won't need to use this." on the official website.

let obj: object = { prop: true };

Union Type

Some variables can have several types.

let greedyVar: string | number;
greedyVar = "Hello"
greedyVar = 7

Type Assertion

Type assertions are a way to tell the compiler "trust me, I know what I'm doing."

A type assertion is like a type cast in other languages, but it performs no special checking or restructuring of data.

It has no runtime impact and is used purely by the compiler.

Type assertions have two forms. One is the as syntax and the other is angle-bracket syntax.

let unknownVar: unknown;
let strLength: number;

unknownVar = "string variable";
strLength = (unknownVar as string).length;
strLength = (<String>unknownVar).length;

When using TypeScript with JSX, only as style assertions are allowed.

Type Alias

The meaning can be further clarified by giving a new name to the type that already exists.

type name = string
type width = number
type id = number | null
type employee = {
  name: string
  id: number
  age?: number
  salary: number
}

? symbol means optional. In other words, this field can be existing or not.

 

You may force only certain values.

type USER_TYPE = 'CUSTOMER' | 'ADMIN'
let user: USER_TYPE
user = 'DEVELOPER' // Error: not assignable

Type Guard

Type guard is used for narrowing the range of type.

typeof

typeof type guard tells us the type of values.

const varA = 7
const varB = "hello"

console.log(typeof varA)  // "number"
console.log(typeof varB)  // "string"

instanceof

instanceof type guard is used to check whether an instance is of a particular class.

class Person {}

const person = new Person()

console.log(person instanceof Person) // true

in

Type guard in is used to check that a particular property is included in an object.

The property you want to check should be used as a string.

interface A { a: number }
interface B { b: number }

function test(param: A | B) {
  if ("a" in param) {
    return param.a
  }
  return param.b
}

Uppercase Type

It can be tempting to think that the types Number, String, Boolean, Symbol, or Object are the same as the lowercase versions recommended above.

These types do not refer to the language primitives, however, and almost never should be used as a type.

'Web > JavaScript' 카테고리의 다른 글

[TypeScript] Singleton Pattern  (0) 2021.07.05
[TypeScript] Class  (0) 2021.07.04
[Vue3] Getting Started with Vue3 + Electron (with Typescript, TailwindCSS)  (0) 2021.06.28
[Vue3] Vuex Usage  (0) 2021.06.26
[Vue3] Mixins  (0) 2021.06.26

댓글