FrontEnd :-)

코딩앙마 타입스크립트 기초강의 본문

TypeScript

코딩앙마 타입스크립트 기초강의

code10 2022. 9. 6. 22:33
//배열 타입
function add(...nums: number[]){
    return nums.reduce((result, num) => result + num, 0);
}

console.log(add(1,2,3)); //6

코딩앙마 타입스크립트 기초

 

#3 interface

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

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

console.log(a(33)); //true
console.log(a(10)); //false

//implements

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

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

const b = new BMW("green");
console.log(b); 
/* 
[LOG]: BMW: {
  "wheels": 4,
  "color": "green"
} 
*/
b.start(); //"go.."

//extends

interface Benz extends Car {
    door: number;
    stop(): void;
}

const benz : Benz = {
    door: 5,
    stop(){
        console.log("stop!");
    },
    color: "black",
    wheels: 4,
    start(){
        console.log("go..")
    }
}

console.log(benz);
benz.stop();
benz.start();

/*
[LOG]: {
  "door": 5,
  "color": "black",
  "wheels": 4
} 
[LOG]: "stop!" 
[LOG]: "go.." 
*/

 

 

#4 함수

//오류코드 => 하나의 매개변수가 필요하다!
function hello(name: string) {
    return `Hello, ${name || "world"}`;
}

const result = hello(); 

//옵셔널 적용, 선택적 매개변수
function hello(name?: string) {
    return `Hello, ${name || "world"}`;
}

const result = hello();
const result2 = hello("Sam");

//매개변수 디폴트 값
function hello(name = "World") {
    return `Hello, ${name}`;
}
//옵셔널하게 사용하고 싶다면
function hello(age?: number, name: string): string { //이거 아니고, 

//undefined 활용
function hello(age: number | undefined, name: string): string {
    if(age !== undefined){
        return `Hello, ${name}. You are ${age}.`;
    } else {
        return `Hello, ${name}`;
    }
}

console.log(hello(30, "Sam"));
console.log(hello(undefined, "Sam"));
interface User {
    name: string;   
}

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

function showName(this:User){
    console.log(this.name)
}

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

// age, gender 추가
function showName2(this:User, age:number, gender:'m'|'f'){
    console.log(this.name, age, gender)
}

const aa = showName2.bind(Sam);
aa(30, 'm');

오버로드

//함수 오버로드? 오버로딩? 사용
//동일한 함수이지만, 매개변수 타입이나 개수에 따라 다른 방식으로 동작해야 한다면 => 오버로드 사용
interface User {
    name: string;
    age: number;
}

function join(naem: 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");

 

#5 리터럴, 유니온/교차 타입

// literal types

const userName1 = "Bob"; // 타입: Bob 
let userName2 = "Tom"; //string 타입으로 정의됨.

//userName3 숫자형 포함하려면
let userName3: string | number = "Tom";
userName3 = 3;

type Job = "police" | "developer" | "teacher";

interface User {
    name: string;
    job: Job;
} 

const user: User = {
    name: "Bob",
    job: "developer",
    // job: "student" 하면 오류남.
}

유니온 타입

// Union types

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

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

//식벽가능한 유니온 타입, 동일한 속성의 타입을 다르게 해서 구분할 수 있느 것;
function getGift(gift: Car | Mobile){
    console.log(gift.color);
    if(gift.name === "car"){
        gift.start();
    } else{
        gift.call();
    }
}

교차 타입

// Intersection types

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

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

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