Typescript from 코딩애플 : Part2-1

27960 단어 typescripttypescript

1. rest / destructing 타입 지정

rest 문법 사용시 타입 지정

...a : number[]

destructing 문법 사용시 타입 지정

function 함수({student, age} : {student:boolean, age:number}){
  console.log(student,age)
}

함수({student:true, age:20});

2. Narrowing 더 알아보기

2.1 &&

// 기존에 알던 문법
function 함수(a : string | undefined):void{
  if( typeof a === 'string') {
    console.log(a)
  }else if() {
  	return
  }
}

// a && 로 null 또는 undefined 처리
function 함수(a : string | undefined):void{
  if(a && typeof a === 'string') {
    console.log(a)
  }
}

2.2 '속성명' in object명

type Fish = {swim :string}
type Bird = {fly : string}

function 함수(animal : Fish | Bird):void{
  if('swim' in animal){
    animal.swim = '123'
  }else if('fly' in animal){
    animal.fly = '123'
  }
}

2.3 'object' instanceof 부모클래스

let 날짜 = new Date()
if(날짜 instanceof Date){
  console.log('처음이에요)
}

2.4 literal 타입으로 구별

type Car = {wheel :'4개', color:string}
type Bike = {wheel :'2개', color:string}

function 함수(x : Car | Bike):void{
  if(x.wheel === '4개'){
    console.log('x'는 Car 타입입니다.)
  }else if(x.wheel === '2개'){
    console.log('x'는 Bike 타입입니다.)
  }
}

3. never타입

never를 쓸수 있는 조건

  1. return 값이 없어야 함
  2. endpoint가 없어야 함
function 함수():never{
  
}

never를 쓰이는 경우

사실 void를 쓰기에 쓸 경우가 없다.
그러나 알아둬야 자동완성으로 never가 뜰때 대체가 가능하다.

경우 #1

function 함수(parameter : string){
  if(typeof parameter === 'string){
    console.log(parameter)
  }else {
    console.log(parameter)    // 이 떄의 parameter의 타입이 never가 된다. 
      // 이 조건문에 들어올수가 없다. (코드를 잘못 짠거다.)
  }
}

4. public, private

public 문법

class User{
  public name = 'kim';      
  // public 붙으면 모든 자식들이 이용 가능
  // 사실 기존에는 public이 생략되어 있는 거다.
  
  constructor(a){
    this.name = a
  }
}
let 유저1 = new User('park')
유저1.name = '안녕'

private 문법

class User{
  private name = 'kim';      
  // public 붙으면 모든 자식들이 이용 가능
  // 사실 기존에는 public이 생략되어 있는 거다.
  
  constructor(a){
    this.name = a
  }
}
let 유저1 = new User('park')
유저1.name = '안녕' // 에러 발생 , private 속성은 읽기만 가능

private 쓰는 경우

class User{
  name;
  private familyName :string = 'kim';
  // 생성되는 모든 자식에서 이속성은 불변이여야 하므로
  // private 를 붙여서 실수로 변경되는 것을 방지
    
  constructor(a){
    this.name = this.familyName + a
  }
}
let 유저1 = new User('민수')
유저1.name // 'kim민수'

긴급하게 private 속성을 변경해야 하는 경우

class User{
  name;
  private familyName :string = 'kim';
  // 생성되는 모든 자식에서 이속성은 불변이여야 하므로
  // private 를 붙여서 실수로 변경되는 것을 방지
    
  constructor(a){
    this.name = this.familyName + a
  }
  
  이름변경함수(){
  	this.familyName = 'park'
  }
}
let 유저1 = new User('민수')
유저1.이름변경함수()

5. protected, static

protected

class User{
  private x = 10;
}

// 복사하고 싶다.
class newUser extends User{   // 에러, private 속성은 복사가 안됨.
  
}

let 사람 = new newUser() 
class User{
  protected x = 10;  // protected 속성은 복사가 가능
}

// 복하하고 싶다.
class newUser extends User{
  
}

let 사람 = new newUser()

static

class User{
  static x = 10;   // static 붙이면 부모만 사용하게 설정
  y = 20;
}

let 자식 = new User()
console.log(자식) // {y: 20}

6. 타입을 Import , export

기본

//a.ts
export var 이름 = 'kim'
export var 나이 = 20
export type Name = string

//b.ts
import {이름 , 나이, Name} from './a.ts'

import , export 생기기 전에 쓰이던 방식

//a.ts
namespace 네임스페이스 {                // 아주 옛날에는 module이라 되어 있다.
  export type Name = string | number;
}
let 변수 : 네임스페이스.Name = 'kim'

//b.ts
/// <reference path="./a.ts" />
네임스페이스.Name

7. Generic

function 함수(x : unknown[]){
  return x[0]
}

let a = 함수([4,2]) // a는 4가 할당되지만 타입은 unknown이 된다.

console.log(a+1)  // 에러가 난다.

Generic 함수 생성

function 함수<Type>(x : unknown[]) :Type{
  return x[0]
}

let a = 함수<number>([4,2]) // a는 4가 할당되고 타입은 number가 된다.

console.log(a+1)  // 실행이 된다.

타입 제한

function 함수<Type>(x :Type) :Type{
  return x - 1                 // 에러 생김
}

let a = 함수<number>(100) 

// 들어오는 타입이 number인지 미리 검사해라
function 함수<Type extends number>(x :Type) :Type{
  return x - 1           // 에러 안생긴다.
}

좋은 웹페이지 즐겨찾기