본문 바로가기
Frontend/TypeScript(완)

[TS] TS연습하기5

by VictorMeredith 2023. 4. 12.

TypeScript

//class 문법과 ts

class Persona {
  personaName:string // 위에서 변수를 미리 만들어놔야 생성자를 사용할 수 있다.
  constructor(name:string){
    this.personaName = name
  }

  메소드(param:string):void{
    console.log(this.personaName + param)
  }
}

let 사람1 = new Persona('이땡땡');
let 사람2 = new Persona('김땡떙');

console.log(사람1)
사람1.메소드('은 가나다')



// interface 문법 : extends가 가능하다. 중복선언이 가능하다.
// 장점 : type을 & 속성으로 연결할 때 중복속성이 발생하면 사용할때만 나중에 에러가 나는데, interface는 미리에러를 발생시켜준다.
interface Square {
  color:string,
  width: number
}

let 네몽:Square = {
  color:'red',
  width: 50
}


//type 키워드 Alias와의 차이점
interface Human {
  name : string,
  age : number,
  roles : string
}

interface Student extends Human{
  school:'elem'|'middle'|'high'
}

const lee:Student = {
  name : 'lee',
  age : 18,
  roles : 'student',
  school : 'high',
  score:100
}


// 참고 : Omit 
interface Student2 extends Omit<Human, 'roles'> {
  roles: number;
}
// Omit 유틸리티 타입을 사용하여 Human 인터페이스에서 roles 속성을 제거한 뒤, 
// Student 인터페이스에 새로운 roles 속성을 number 타입으로 추가한다.
// 이렇게 하면 roles 필드를 Overriding 하고 숫자 할당이 가능하다.


//interface는 중복선언이 가능하다.
interface Student { //중복선언을 하면 자동으로 추가된다. (타입자체는 중복이 되지 않는다.)
  score : number
}

'Frontend > TypeScript(완)' 카테고리의 다른 글

[TS] TS연습하기7  (0) 2023.04.12
[TS] TS연습하기6  (0) 2023.04.12
[TS] TS연습하기4  (0) 2023.04.12
[TS] TS 연습하기3  (0) 2023.04.12
[TS] TS 연습하기2  (0) 2023.04.12

댓글