TypeScript

2021. 12. 5. 11:17Frontend/Web programming

    목차
반응형

variable decralation

let var1 = 'var1';
let var2: string = 'var2';
let var3: any = 'var3';
var3 = 1;

function

function func(arg1: string, arg2: number=10): number {
   ...
}

function func(arg1: string, arg2?: number): number {
   ...
}

arrow

There are no need to designate 'return' keyword.

let afunc = () => 'res';

this

arrow function 내에서 this는 현재 scope의 this

``typescript
function afunc(arg: string) {
this.arg = arg

setInterval(
    () => {
        console.log('arg = ', this.arg)  // test
    }
, 100)

}

let ret = new afunc('test')


function에서의 this는 전역의 this 즉, window

``typescript
function afunc(arg: string) {
    this.arg = arg

    setInterval(
        function() {
            console.log('arg = ', this.arg)  // undefined
        }
    , 100)
}

let ret = new afunc('test')

class

class Animal {
  name: string
  species: string
}

var animal = new Animal()
animal.name = 'Kabin'
animal.species = 'dog'
class Animal {
  name: string
  species: string

  constructor(name: string, species: string) {
    this.name = name
    this.species = species
  }
}

var animal = new Animal('Kabin', 'dog')

access modifier

class Animal {
  public name: string
  private _species: string

  constructor(name: string, species: string) {
    this.name = name
    this._species = species
  }
}

var animal = new Animal('Kabin', 'dog')
console.log(animal._species)  // error
class Animal { 
  constructor(public name: string, private _species: string) {
    ...
  }
}

var animal = new Animal('Kabin', 'dog')
console.log(animal._species)  // error

constructor에서만 선언해도 member 변수들이 할당됨

method

class Animal {
  public name: string
  private _species: string

  constructor(name: string, species: string) {
    this.name = name
    this._species = species
  }

  doSomething(arg: number): void {
    ...
  }
}

var animal = new Animal('Kabin', 'dog')
console.log(animal._species)  // error
class Animal { 
  constructor(public name: string, private _species: string, private _age: number) {
    ...
  }

  get age(): number {
    return this._age
  }

  set age(val: number): number {
    return this._age = val
  }
}

var animal = new Animal('Kabin', 'dog')
console.log(animal._species)  // error

inheritance

class Dog extends Animal {
  breed: string

  constructor(public name: string, private _species: string, breed: string) {
    super(name, _species)
    this.breed = breed
  }
}

generics

class Animal {
  name: string
}

class Dog extends Animal {
  breed: string
}

class Insact {
  name: string
}

let animals: Array<Animal> = []
animals[0] = new Dog()
animals[1] = new Animal()
animals[2] = new Insact()  // error

use 'generics' as a parameter

function afunc<T>(arg: T) {
  ...
}

afunc<string>('str')
afunc<number>(222)

interface

interface IAnimal {
  name: string

  bark(): boolean
}

class Dog implements IAnimal {
  bark(): boolean {
    console.log('bow wow')
  }
}
반응형