Typescript

[Typescript] Type / interface 함수정의 / 함수 type 정의

sian han 2022. 12. 3. 21:09

Typescript = javascript + type

Javascript 는 Dynamic Typing 가능 => 프로젝트가 커질수록 유연성이 높은 것은 좋지않다.

 

Typescript 는 type을 엄격하게 관리해준다.

  - 에러메세지를 통해 정확하게 에러를 짚어줌

 

 

ex )

function add(num1, num2){
	console.log(num1,num2);
}

 

Javascript

add(); //NaN
add(1); //Nan

 

Typescript

add(); // error : num1:any
add(1); // error : Expected 2 arguments, but got 1

 

 

※ Typescript

▷ 선언

let car:string = 'bmw';
let car:string // 타입 추론
let age:number =30;
let isAdult:boolean =true;
let a:number[] = [1,2,3];
let a2:Array<number> = [1,2,3];

let week1:string[] = ['mon','tue','wed'];
let week2:Array<string> = ['mon','tue','wed'];

 

▷ 튜플 

  - 배열과 비슷한 모양인데 인덱스 별로 자료형이 다른 경우 사용

let b:[string,number];

b=['z',1];
b=[1,'z']; // error

b[0].toLowerCase();
b[1].toLowerCase(); // error

 

 

▶ Type

 

▷ void

  - 아무것도 반환하지 않을때

 

 never

  - 항상 에러를 반환하거나 영원히 끝나지 않는 함수의 타입으로 사용가능

 

 enum

  - 열거형 타입

  - enum 에 값을 할당하지 않으면 index 값으로 자동 지정됨

 

 null, undefined

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

 

 

▶ interface 함수 정의

 

객체는 object 라는 타입으로 정의 가능하다

let user:object;

user = {
	name : 'sian',
    age : '23'
}

console.log(user.name) // error
 - object 에는 특정속성값에 대한 정보가 없기 때문에 error 발생

 

 = > property 를 정해서 객체로 사용하고자 할때는 interface 를 사용한다

interface User {
	readonly name : string;
    age : number;
}

let user : User = {
	name : 'sian',
    age : 23
}

console.log(user.age) //23
user.name = 'seohyun' //error : 읽기전용이기 때문

readonly - 읽기전용, 수정불가

 

ex ) 나이를 입력하면 성인인지 아닌지 boolean 을 리턴하는 함수

interface IsAdult {
	(age:number):booleean;
}

const a:IsAdult = (age) =>{
	return age > 19;
}

a(22); //true

 

interface 로 class 정의 : implement

interface Car{
	color:string;
    wheels:number;
    start():void;
}

class Bmw implements Car{
	wheels = 4;
    
    constructor(c:string){
    	this.color =c;
    }
    
    start(){
    	console.log('go..');
    }
}

const b = new Bmw('green');
console.log(b)
b.start();

 

 

▶ 함수 type 정의

 

▷ return void

function add(num1: number, num2 : number) : void{
	console.log(num1 + num2);
}

 

 return boolean

function isAdult(age: number) : boolean{
	return age > 19;
}

 

 함수의 매개변수를 optional 로 지정

function hello(name?:string):string{
	return 'Hello, ${name || "world"}'; //name 이 있으면 name 을 쓰고, 없으면 world 를 써라
}	
const result = hello(); // Hello, world
const result2= hello('sian'); //Hello,sian

위처럼 optional 을 사용하고 싶으면 name뒤에 ? 를 꼭 써줘야 한다.

 

 

 함수의 매개변수에 default 값 지정

function hello2(name = "world"){
	return 'Hello, ${name}';
}

 

 

 나머지 매개변수의 type 작성법

function add(...nums: number[]){
	return nums.reduce((result,num)=>result + num,0);
}

... 을 사용하면 전달받은 매개변수를 배열로 나타낼 수 있게 한다.

따라서 ...nums 의 타입은 number[] 가 된다

 

▷ this

interface User{
	name : string;
}

const Sam : User = {name:'Sam'}

function showName(this.User){ //this 의 타입을 지정해줌
	console.log(this.name)
}

const a = showName.bind(Sam);
a(); // "Sam"