Typescript 문법 class/extends/function/Literal types/Union types/intersection types/Generics)
2022. 11. 3. 13:20ㆍTypescript
1. class 정의
클래스는 implements 를 사용한다
interface Car{
color:string; // 타입이 string인 함수
wheels:number; // 타입이 number인 함수
start():void; // return 값이 없는 함수
}
class Bmw implements Car{
color; // 멤버 변수
wheels=4; // js 와 다르게 class 의 멤머변수를 설정할 때 constructor 외부에서도 변수선언을 해주어야 한다
constructor(c:string){ // 생성자 함수
this.color=c;
}
start():void{ // 멤버 함수
console.log('go....!');
}
}
const car1 = new Bmw('green');
console.log(car1);
car1.start();
2. extends ( 확장 )
부모 interface 를 상속받아 코드의 중복을 줄일 수 있다
interface Car{ // 부모 interface
color:string;
wheels:number;
start():void;
}
//interface Car2{ //상속을 사용하지 않고 또다른 interface를 만들면 코드의 중복이 일어난다
// color:string;
// wheels:number;
// door:number;
// start():void;
// stop():number;
//}
interface Car2 extends Car{ // Car2 에 Car 의 class 를 대입해 확장시킨다
//color:string;
//wheels:number; //Car 로부터 상속받는 값
//start():void;
door:number;
stop():void;
}
class Bmw implements Car{
color;
wheels=4;
constructor(c:string){
this.color=c;
}
start():void{
console.log('Bmw go....!');
}
}
const car1 = new Bmw('green');
console.log(car1);
car1.start();
class Benz implements Car2{ // Car2에 Car를 extends 로 상속시켜 Car의 class 타입을 사용 가능하다
color='red'; //Car 로부터 상속받은 값
wheels=4; //Car 로부터 상속받은 값
door;
constructor(c:number){
this.door=c;
}
start():void{ //Car 로부터 상속받은 값
console.log('Benz go....!');
}
stop():number{
console.log('Benz stop....!');
return this.door;
}
}
const car2 = new Benz(4);
console.log(car2);
car2.start();
let aaa:number = 0;
aaa = car2.stop();
console.log(aaa);
2-1. extends 예시
extends 부모, 부모 를 사용해 여러개의 부모 class 를 상속받을 수 있다
interface Car{
color:string;
wheels:number;
start():void;
}
interface Toy{
name:string;
open():void;
}
interface ToyCar extends Car,Toy{
price:number;
buy():void;
}
class Product implements ToyCar{
color='red';
wheels=4;
name='doll';
price=500;
start():void{
console.log('start....!');
}
open():void{
console.log('open stop....!');
}
buy():void{
console.log('buy stop....!');
}
}
const person1 = new Product();
console.log(person1);
person1.start();
person1.open();
person1.buy();
3. 함수 타입 정의 방법
function hello(name?:string):string{ // 변수? - 선택적 매개변수
// if(name){
// return `hello,${name}`
// }else{
// return `hello, 유단자`
// }
return `Hello, ${name || "world"}`;
}
const result = hello();
const result2 = hello('kim');
3-1. 나머지 매개변수, 배열함수
function add(...nums:number[]):number{
return nums.reduce((result,num)=> result + num);
}
console.log(add(1,2,3));
console.log(add(1,2,3,4,5,6,7,8,9,10));
3-2. return 값의 객체 값 타입 설정
interface User{
name:string;
age:number;
}
function join(name:string, age:number):User{
return{
name,
age
};
}
function join2(name:string, age:number):{name:string, age:number}{
return{
name,
age
};
}
const person1:User = join('홍길동',60);
console.log(person1);
3-3. 화살표 함수
interface User{
name:string;
age:number;
}
interface Func{
(name:string, age:number): User;
}
const join:Func = (name,age) =>{
return{
name,
age
};
}
const person1:User = join('홍길동',60);
console.log(person1);
4. 리터럴 ( Literal types ) / 유니온 ( Union types ) / 교차타입 ( intersection types )
4-1 유니온
const userName1 = 'Bob'; // type : Bob ( 상수 )
let userName2 = 'Tom'; // type : string
let userName3:string | number = 'Kim'; // type : string | number
userName3 = 100;
console.log(userName1,userName2,userName3);
4-2 교차타입 => & 여러개의 타입을 하나로 합친다
interface Car{
name: string; // 공통으로 들어가는 값은 key값과 type 값이 일치해야한다
start():void;
}
interface Toy{
name:string; // 공통으로 들어가는 값은 key값과 type 값이 일치해야한다
color:string;
price:number;
}
const toyCar : Toy & Car = { // 합집합의 개념
name:'버스',
color:'blue',
price:10000,
start(){
console.log(this.name,this.color,this.price+'원');
}
}
toyCar.start();
5. 클래스
class Car{
color:string; // 생략시 javascript 에서는 에러가 발생하지 않지만 typescript 에서는 변수를 미리 선언해 주어야 에러가 발생하지 않는다
constructor(color:string){
this.color = color;
}
start(){
console.log(this.color + " car start!");
}
}
const bmw = new Car("red");
bmw.start();
5-1. public 사용
class Car{
//color:string;
constructor(public color:string){ // public 을 앞에 붙여주어 constructor 밖에서 변수를 선언해준 것과 같은 효과
this.color = color;
}
start(){
console.log(this.color + "car start!");
}
}
const bmw = new Car("red");
bmw.start();
5-2 readonly 사용
class Car{
//color:string;
constructor(readonly color:string){
this.color = color;
}
start(){
console.log(this.color + "car start!");
}
}
const bmw = new Car("red");
bmw.start();
//bmw.color='red'; //에러 : 읽기 전용이라 값을 바꿀 수 없다
5-3 접근 제한자 (Access Modifier );
- public -> 자식 클래스, 클래스 인스턴스 모두 접근 가능(생략하면 기본값)
- private -> 해당 클래스 내부에서만 접근 가능(자식 클래스 사용 불가)
- protected -> 자식클래스에서 접근 가능/ 클래스 인스턴스에서 접근 불가
class Car{
public name:string = "똥차";
color:string;
constructor(color:string){
this.color = color;
}
public start(){
console.log('부모클래스 start!',this.name,this.color);
}
}
class Bmw extends Car{
constructor(color:string){
super(color);
}
showName(){
console.log('자식클래스 start!',this.name,this.color);
}
}
const mycar = new Bmw("red");
mycar.start();
mycar.name = "새차"; // 인스턴스에서 직접 값을 바꿀 수 있다
mycar.showName();
6. 제네릭 ( Generics )
제네릭은 특정 타입을 이용해서 템플릿처럼 함수를 만들 수 있다
6-1 함수의 매개변수 전달인자의 타입이 다를 때
6-1-1. 유니온 타입 사용
function getSize(arr:number[] | string[]):number{
return arr.length
}
const arr=[1,2,3];
console.log(getSize(arr));
const arr2 = ['a','b','c','d','e'];
console.log(getSize(arr2));
6-1-2. 제네릭( Generics ) 사용 function 함수명 <타입파라미터>(매개변수:타입파라미터):타입{}
- 유동적으로 변화할 수 있는 타입
function getSize<T>(arr:T[]):number{ //<타입파라미터> -> <T>,<A>,<X>... 아무값이나 사용가능 하다
return arr.length;
}
const arr = [1,2,3];
console.log(getSize<number>(arr)); // <타입파라미터> 안에 실제 타입값을 적용한다
const arr2 = ['a','b','c','d','e'];
console.log(getSize<string>(arr2));
const arr3 = [true,false,false,true];
console.log(getSize<Boolean>(arr3));
ex) 제네릭 interface 활용
interface Mobile<T>{
name:string;
price:number;
option:T;
}
// const obj1:Mobile<object> = {
// name:'삼성 s20',
// price : 100,
// option:{
// color:'red',
// coupon:false
// }
// };
const obj1:Mobile<{color:string; coupon:boolean}> = {
name:'삼성 s20',
price:100,
option:{
color:'red',
coupon:false
}
};
console.log(obj1.name,obj1.price+'만원','색상:'+obj1.option.color,'쿠폰:'+obj1.option.coupon)
const obj2:Mobile<string> = {
name:'삼성 s22',
price:120,
option:'android OS'
};
console.log(obj2.name,obj2.price+'만원');
'Typescript' 카테고리의 다른 글
| Typescript 초기 세팅 / 이론 / 문법 (2) | 2022.11.02 |
|---|