Node.js & TypeScript

[TypeScript] ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ ํƒ€์ž…์ •์˜

martinooo 2022. 11. 11. 11:04

๐Ÿคณ TypeScript ๊ธฐ๋ณธ ํƒ€์ž… ์ •๋ฆฌ


๋ฌธ์ž์—ด ํƒ€์ž…์„ ์ •์˜ ํ•˜๋Š” ๋ฐฉ๋ฒ• 

//string ํƒ€์ž… ์ •์˜
let name: string = 'YOO';

์ˆซ์ž์— ํƒ€์ž…์„ ์ •์˜ ํ•˜๋Š” ๋ฐฉ๋ฒ• 

//number ํƒ€์ž… ์ •์˜  
let age:number = 30;

Boolean true/false ํƒ€์ž…์„ ์ •์˜

//boolen ํƒ€์ž… ์ •์˜ 
const isChk: boolean = false;
let isAdult: boolean = true;

Array ํƒ€์ž…์„ ์ •์˜ ํ•˜๋Š” ๋ฐฉ๋ฒ• 

//array 2๊ฐ€์ง€ ํƒ€์ž… ์ •์˜ ๋ฐฉ๋ฒ•
let array:number[] = [1, 2, 3]
let array2: Array<number> = [1, 2, 3]

ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜๊ฐ’์— ํƒ€์ž…์„ ์ •์˜ ํ•ด์ค„ ์ˆ˜ ์žˆ๋‹ค. 

//return ๊ฐ’์ด ์—†์„๋•Œ๋Š” ๊ฐ’์ด ์—†์œผ๋ฏ€๋กœ void ์ •์˜ํ•ด์ค„์ˆ˜์žˆ๋‹ค.
function introduce(): void{
    const a = 1
}
//never error ๋ฐ˜ํ™˜ํ•˜๊ฑฐ๋‚˜ ์˜์›์ด ๋๋‚˜์ง€ ์•Š๋Š” ํ•จ์ˆ˜์— ์ •์˜ ํ• ์ˆ˜์žˆ๋‹ค. 
function cutError(): never{
    throw new Error();
}
//ํ•จ์ˆ˜์— return ๊ฐ’์ด ๋ฌธ์ž์—ด์ด๋ผ๋ฉด ๋ฌธ์ž์—ด์— ํƒ€์ž…์„ ์ •์˜ํ•ด์ค„์ˆ˜์žˆ๋‹ค 
function fun():string {
    return 'string'
}

๐Ÿ‘€ ์‘์šฉ


//ํ•จ์ˆ˜์— ์ธ์ž ๊ฐ’์œผ๋กœ age๋ฅผ ๋…๊ฒจ์ฃผ๊ณ  return ๊ฐ’์€ boolean ๊ฐ’์ผ ๊ฒฝ์šฐ
function fun2(age: number): boolean{
    return age > 19
}
//ํ•จ์ˆ˜์— return ๊ฐ’์ด ๊ฐ์ฒด ์ผ๊ฒฝ์šฐ
function fun3(): object{
    const data = {
        name : 'yoo',
        age : 30
    };

    return data;
}

 


null & undefined ํƒ€์ž…์ •์˜

//null, undefined 
const a:null = null;
const b:undefined = undefined;