1. 클래스 생성자 매써드 - 매개변수

// 매개변수 미리 선언하기
class Car {
    color: string; // 아래의 생성자매서드에 사용된다면, 미리 선언을 해줘야 한다.

    constructor(color: string) {
        this.color = color;
    }
}

// 또는, 생성자 매서드의 매개변수에 'public' 또는 'readonly' 
class Car {
    constructor(public color: string) {  
        this.color = color;
    }
}

const bmw = new Car("red")

 

 

2. 접근 제한자 (Access modifier) : public

// Car클래스
class Car {
    name: string = "car"  // public name: string = "car" 와 동일
    color: string;
    constructor(color: string) {
        this.color = color;
    }
    start() {
        console.log("start")
    }
}

// 자식클래스
class Bmw extends Car {   
    constructor(color: string) {
        super(color);
    }
    showName() {
        console.log(super.name)  // 자식클래스에서 사용가능
    }
}

const z4 = new Bmw("black")  // 클래스 인스턴스 접근 가능

 

 

3. 접근 제한자 (Access modifier) : private

// Car클래스
class Car {
    private name: string = "car"  // #name: string = "car" 와 동일
    color: string;
    constructor(color: string) {
        this.color = color;
    }
    start() {
        console.log("start")
        console.log(this.name)   // Car 클래스에서만 내부에서만 사용가능(자식클래스에서 사용불가)
                                 // console.log(this.#name)로도 표현 가능
    }
}

 

 

4. 접근 제한자 (Access modifier) : protected

class Car {
    protected name: string = "car" 
    color: string;
    constructor(color: string) {
        this.color = color;
    }
    start() {
        console.log("start")
    }
}

// 자식클래스
class Bmw extends Car {   
    constructor(color: string) {
        super(color);
    }
    showName() {
        console.log(super.name)  // 자식클래스에서 사용가능
    }
}

const z4 = new Bmw("black")
console.log(z4.name) // 에러발생: 클래스 인스턴스로 접근 불가

 

 

5. static 정적 멤버 변수

// static 정적 멤버 변수
class Car {
    name: string = "car";
    static wheels = 4;

    start() {
        console.log("start")
        console.log(this.name)
        console.log(Car.wheels)  // static을 사용할때는, this가 아닌 Class명을 적어야한다.
    }
}

console.log(Car.wheels)

 

 

6. 추상 클래스

abstract class Car {
    color: string;
    constructor(color: string) {
        this.color = color
    }
                  
    abstract doSometing():void // 상속받는 곳에서 '구체적인 기능'을 구현해주어야 함
}

// const car = new Car("red")  // 오류 발생: 추상 클래스는 new를 이용해서 객체를 만들 수 없음

class Bmw extends Car {        // 오직 상속을 통해서만 객체를 만들 수 있음
    constructor(color: string) { 
        super(color);
    }

    doSomething(){             // 상속받는 곳에서 '구체적인 기능'을 구현해줌
        alert(3)
    }
}

const z4 = new Bmw("black")

 

1. 문자열(리터럴) 타입

const userName1 = "Bob"    // 변경되지 않는 변수 선언
let userName2: string | number = "Tom"  // 이후 변수를 변경

 

 

2. 유니온 타입 : 자바스크립트의 OR 연산자 || 

interface Car {
  name: "car";
  color: string;
  start(): void;
}

interface Mobile {
  name: "mobile";
  color: string;
  call(): void;
}

// 식별가능한 유니온 타입
function getGift(gift: Car | Mobile) {
  if (gift.name === "car"){
    gift.start()
  } else {
    gift.call()
  }
}

 

 

3. 교차파입 : 여러타입을 합쳐서 사용

interface Car {
  name: string;
  start(): void;
}

interface Toy {
  name: string;
  color: string;
  price: number;
}

const toyCar: Toy & Car = {
  name: "타요",
  start(){},
  color: "blue",
  price: 1000
}

1. 함수 작성

const add = (num1: number, num2: number):void => {
  console.log(num1 + num2)
}

 

 

2. 선택적 매개변수

const hello = (name?: string) => {
  return `Hello, ${name || 'world'}`
}

hello() // Hello, world
hello('purple') // Hello, purple

 

 

3. 매개변수 옵션값

// 옶션값이 뒤에 있는 경우
const hello = (name: string, age?: number): string => {
 if (age !== undefined) {
  return `Hello, ${name}. You are ${age}.`;
 } else {
  return `Hello, ${name}.`;
 }
}

hello('Sam',30) // "Hello, Sam. You are 30." 
hello('Sam')    // "Hello, Sam." 

// 옶션값이 앞에 있는경우
const hello2 = (age: number | undefined, name: string): string => {
 if (age !== undefined) {
  return `Hello, ${name}. You are ${age}.`;
 } else {
  return `Hello, ${name}.`;
 }
}
 
hello2(undefined,'Sam')  // "Hello, Sam."

 

 

4. 나머지 매개변수

const add = (...nums: number[]) => {
 return nums.reduce((acc,cur) => acc + cur, 0)
}

add(1,2,3) // 6

 

 

5. This 

// 1. interface
interface User {
  name: string;
}

// 2. interface로 객체 Sam 생성
const Sam: User = { name:'Sam'}

// 3. 함수 설정 (화살표 함수로 작성하면 오류가 생긴다)
function showName(this:User ,age:number, gender:'m'|'f') {
  console.log(this.name, age, gender)
}

const getSame = showName.bind(Sam) // showName함수가 Sam 객체를 보여주도록 함

getSame(30,'m') // "Sam",  30,  "m"

 

 

6. 매개변수 타입에 따라 결과가 다를 때

// 1. interface
interface User {
  name: string
  age: number
}

// 2. 오버로드를 사용해서 타입에 따른 결과를 다를게 설정
function join(name: string, age: number): User;
function join(name: string, age: string): string;
function join(name: string, age: number | string): User | string {
  if (typeof age === 'number') {
    return {
      name,
      age
    }
  } else {
    return "나이를 숫자로 입력해주세요"
  }
} 

const sam : User = join("Sam", 30)
const jane : string = join("Jane","30")

1. 인터페이스 및 초기값 설정 

type Score = 'A' | 'B' | 'C' | 'D' | 'F'  


// 1. Interface
interface User {
    name : string;     // 필수
    age : number;      // 필수
    gender? : string;  // 옵션
    readonly birthYear : number;  // 읽기 전용 (수정X)
    [grade : number] : Score;  // 키:number, 값:Score 인 프로퍼티를 여러개 받을 수 있음
}


// 2. Interface 기준으로 초기값 설정
let user : User = {  
    name : 'xx',
    age: 30,
    birthYear : 2000,
    1 : 'A',
    2 : 'B',
}

console.log(user.age) // 30

 

 

2. 인터페이스로 함수 정의

// 1. Interface
interface Add {
  (num1: number, num2: number): number;

}

// 2. Interface를 이용해서 함수 생성
const add : Add = (x,y) => {
  return x + y
}

console.log(add(3,5))  // 8

 

 

3. 인터페이스로 클래스 정의

// 1. Interface
interface Car {
  color: string;
  wheels: number;
  start(): void;
}

// 2. Interface 이용해서 클래스 생성
class Bmw implements Car {
  color;
  wheels = 4;
  constructor(c:string) {  // 생성될때 color를 입력받기
    this.color = c;
  }
  start(){
    console.log('go..')
  }
}

const b = new Bmw('green')
console.log(b) // Bmw: { 'wheels': 4, 'color': 'green'}
b.start() //  "go.."

 

 

3-1. 인터페이스 확장

// 1. Interface
interface Car {
  color: string;
  wheels: number;
  start(): void;
}

// 1-2. Interface 확장
interface Benz extends Car {
  door: number;
  stop(): void;
}

// 1-3. Interface 기준으로 초기값 작성
const benz : Benz = {
  door : 5,
  color : 'black',
  wheels : 4,
  stop(){
    console.log('stop')
  },
  start(){
    console.log('go..')
  }
}

 

 

3-2. 인터페이스 확장

// 1. Car Interface
interface Car {
  color: string;
  wheels: number;
  start(): void;
}

// 2. Toy Interface
interface Toy {
  name: string;
}

// 3. Car와 Toy의 인터페이스 확장
interface ToyCar extends Car, Toy {
  price : number;
}

 

1. 문자

let color = 'purple';  // 'purple'을 자동적으로 string으로 인식 (다른 타입도 마찬가지)
let color:string = 'purple'

 

 

2. 숫자

let age:number = 30

 

 

3. 불리언

let isAdult:boolean = true;

 

 

4. 숫자/ 문자열 배열

let arr:number[] = [1,2,3]  //숫자 배열

let arr:string[] = ['a','b','c']  //문자열 배열1
let arr:Array<string> = ['a','b','c']  //문자열 배열2

 

 

5. 튜플

let b:[string, number] // 첫번째 인자: 문자 , 두번째 인자: 숫자

b = ['a',1]

 

 

6. void / never

void : 함수에서 아무것도 반환하지 않을 때 사용함

const sayHello = ():void =>{
	console.log('hello')
}

sayHello()

naver : 항상 에러를 반환하거나 끝나지않는 함수 타입으로 사용함

const showError = ():never => {
	throw new Error()
}

const infLoop = ():never => {
	while(true) {
    	// do something
    }
}

 

 

7. enum 

enum : 비슷한 값을 묶어 주는, 열거형 데이터

enum Os {
    Window = 3, // 기본적으로 0부터 순차적으로 할당됨 (3으로 작성시 3으로 할당, 3부터 순차적으로 할당됨)
    Ios, 
    Android
}

console.log(Os[3])  // Window
console.log(Os['Window'])  // 3

let myOs:Os  // Os의 값만 넣을 수 있다

myOs = Os.Window

 

 

8. null / undefined

let a:null = null
let b:undefined = undefined

Node.js를 주로 사용하지만, 타입스크립트의 요구가 늘어나는 것같아 배워보고자 한다.

 


 

Javascript는 동적언어라, 런타임에 타입이 결정되고 오류를 발생시킨다. 

코드상에는 오류가 발생하지 않았지만, 의도하지 않은 결과가 나타난다.

 

 

하지만, typescript(나 Java)는 정적언어라 컴파일 타임에 타입이 결정되고 오류를 발생시킨다.

아래처럼 아직 실행시키지도 않았는데, 오류들이 나타난다.

 

 

typescript 사용할때에는 type을 설정해줘야한다.

의도한 대로 사용하지 않으면 오류를 보여준다. 

 

+ Recent posts