Typescript - type(1)

ryan·2022년 5월 5일
0

Type?

  • TypeScript는 JavaScript 코드에 변수나 함수 등 Type을 정의할 수 있음
  • Type을 나타내기 위해 타입 표기(Type Annotation)을 사용함.

number

const num: number = 1;

string

const str: string = "string";

boolean

const bool: boolean = true;

array

const arr: Array<number> = [1, 2, 3];
  • <>안에 어떤 타입의 배열을 받게 되는지 명시함(제네릭)

함수 표현

const addOne: (value: number) => number = (value: number) => value + 1;
  • (value:number)=>number 까지가 타입
    • value의 타입이 넘버이고, return도 number이다 라는 뜻

tuple

const tuple: [number, number, number] = [1, 2, 3];
  • 길이와 각 요소의 타입이 정해진 배열을 저장

optional

function sayHello(target?: string) { // target은 string or undifined
const t = target ?? "World"; // ?? > target이 null이거나 undifined인경우  "World"로 할당해라.
  console.log(`Hello, ${t}`); 
}
sayHello("Mike"); // result > Hello, Mike
sayHello(); // result > Hello, World

interface

interface Machine {
  type: string;
  name: string;
  run: () => void;
  getType: () => string;
}
  • 객체의 형태와 타입을 미리 정의해놓음
interface G {
  name : String;
}
interface G {
  age : Number;
}

// === interface G{
//  name:String;
//  age:Number;
// }
  • 위와 같이 객체에 계속 추가할 수 있음.

class

class Animal {
  id: number; // 각 state에 타입지정
  name: string;
  private secret: string; // private 클래스 내부에서만 값을 적용하겠다는 의미, default > public

  constructor(name: string) {
    this.id = Date.now();
    this.name = name;
    this.secret = "this is secret";
  }

  public getName() {
    this.logSecret();
    return this.name;
  }

  private logSecret() {
    console.log(`${this.secret}`);
  }
}
profile
프론트엔드 개발자

0개의 댓글