타입스크립트 함수와 methods 에 type alias, html 변경조작, class 만들때 타입지정

column clash·2021년 8월 22일
0

함수선언식.

type 함수타입 = (a: string) => number;
type NumOut = (x : number, y : number ) => number ;

let 함수테스트: 함수타입 = function (a) {
  return 10;
};

type 함수타입 = 매개변수 => 리턴값

type Member = {
	name : string,
    age : number,
    plusOne : (x:number) => number;
    changeName : () => void;
}

let 회원정보: Member = {
  name: "kim",
  age: 30,
  plusOne(x) {
    return x + 1;
  },
  changeName: () => {
    console.log("안녕");
  },
};

html 변경조작. Narrowing 기억

compilerOptions 변경

{
    "compilerOptions": {
        "target": "ES5",
        "module": "commonjs",
        "strictNullChecks": true  --> 추가
    }
} 
let 제목 = document.querySelector("#title");
Narrowing
if (제목 !== null) {
 제목.innerHTML = "반가워요";
}

let 제목 = document.querySelector("#title") as Element

가장 많이 쓰이는 것.

// 가장 많이 쓰이게 될 것.
if (제목 instanceof Element) {
  제목.innerHTML = "반가워요";
}
물음표. 옵셔널 체이닝 (optional chaining)
if (제목?.innerHTML) {
제목.innerHTML = "반가워요";
}

strictNullChecks 을 false 하거나 없애줘도 된다.
let 링크 = document.querySelector(".link");
if (링크 instanceof HTMLAnchorElement) {
  링크.href = "https://kakako.com";
}
let 버튼 = document.querySelector("#button");
버튼?.addEventListener("click", function () {});

let 링크2 = document.querySelectorAll(".naver");

링크2.forEach((a) => {
  if (a instanceof HTMLAnchorElement) {
    a.href = "https://kakao.com";
  }
});

class Person321 {
  name: string;
  constructor(a: string) {
    this.name = a;
  }
  함수(a: string) {
    console.log("안녕" + a);
  }
}

let 사람122 = new Person321("kim");
let 사람123 = new Person321("jun");
사람122.함수("안녕");

class Car {
  name: string;
  price: number;
  constructor(name: string, price: number) {
    this.name = name;
    this.price = price;
  }
  tax(): number {
    return this.price * 0.1;
  }
}

let car1 = new Car("소나타", 3000);
console.log(car1);
console.log(car1.tax());

class World {
  num: number[];
  str: string[];
  constructor(...rest: number[] | string[]) {
    this.num = [];
    this.str = [];
    rest.forEach((a) => {
      if (typeof a === "string") {
        this.str.push(a);
      } else {
        this.num.push(a);
      }
    });
  }
}
profile
풀스택 개발 중...

0개의 댓글