타입 스크립트(1)

Jeon seong jin·2020년 5월 3일
0

typeScript

목록 보기
1/1

환경 준비

  • vscode : $ yarn init -y 혹은 yarn init으로 프로젝트 생성
  • 프로젝트가 생성이 되면서 package.json 이라는 파일이 생성된다.

타입스크립트 설정파일 생성하기

  • 그 다음에는 설정파일 tsconfig.json을 직접 생성하거나, 명령어를 사용하여 생성 할수도 있다.
    먼저, typescript를 글로벌로 설치를 해 주어야 한다.

yarn global add typescript

  • 그 다음에 명령어를 이용하여 tsconfig.json파일을 자동 생성하자.
    npx tsc --init

  • 명령어로 생성된 tsconfig.json 안에 outDir 속성을 추가하자.

{
  "compilerOptions": {
    "target": "ES2015",
    "module": "commonjs",
    "strict" : true,
    "outDir": "./dist"
    "esMouleInterop":true
  }
}

타입스크립트 파일 만들기

  • src 디렉토리를 만들고 그안에 ts파일을 작성
const message: string = 'hello world';

: string이라는 코드는 해당 상수 값이 문자열이라는 것을 명시해준다.

  • 코드를 모두 작성하였다면 tsc 명령어를 입력하고 입력이 되면 js파일이 생성된다.
  • 생성되면서 ts파일에 명시한 값의 타입은 컴파일이 되는 과정에서 모두 사라지게 된다.
  • 우리는 글로벌로 설치한 타입스크립트 cli를 통해 코드를 컴파일 한 것이고, 만약 프로젝트 내에 설치한 typescirpt 패키지를 사용하고 컴파일 하고 싶을 땐 다음 명령어를 이용하자.
    $ yarn add typescript

그 다음에는 package.json 파일을 열어 다음과 같이 스크립트를 만든다.

{
  ...
  "scripts":{
    "build": "tsc"
  }
}

기본 타입

let count = 0; //숫자
count += 1;
count = '갑분문'; //에러 발생

const message: string = 'hello'; //문자열

const done: boolean = true; // 불리언 값

const numbers: number[] = [1, 2, 3]; // 숫자 배열

const messages: string[] = ['lll', 'wwkwkwk', 'Rnld']; //문자열 배열

messages.push(1); // 에러를 발생시킨다. 문자열 배열이기 때문에..

let mightBeUndfined: sring | undefined = undefined; // string 일수도 있고 undefined

함수에서 타입 정의하기

const sum = (x:number,y:number) :number {
return x + y;
}
sum()
  • 위 코드의 첫번째 줄의 가장 우측을 보면 ): number 가 있다 해당 함수의 결과물이 숫자라는것을 명시합니다.
const sumArray = (numbers: number[]): number => {
  return numbers.reduce((acc, current) => acc + current, 0);
};
const total = sumArray([1, 2, 3, 4, 5]);
  • 타입스크립트를 사용했을 떄 편리한 점은, 배열의 내장함수를 사용 할 때도 타입 유추가 매우 잘 이루어진다는 것입니다.
  • 참고로 함수에서 만약 아무것도 반환하지 않아야 한다면 이를 반환 타입void로 설정하면 됩니다.
const returnNot = (): void => {
  console.log('I am not');
};
returnNot();

interface 사용하기

  • interface는 클래스 또는 객체를 위한 타입을 지정 할 때 사용되는 문법입니다.

클래스에서 interface를 implements 하기

우리가 클래스를 만들 떄, 특정 조건을 준수해야 함을 명시하고 싶을 때 interface를 사용하여 클래스가
가지고 있어야 할 요구사항을 설정합니다. 그리고 클래스를 선언 할 때 implements키워드를 사용하여 해당 클래스
특정 interace의 요구사항을 구현한다는 것을 명시합시다.

// Human이라는 interface를 선언

interface Human {
  getArea(): number; //Human interface 에는 getArea 라는 함수가 꼭 있어야 하며 해당 함수의 변환값을 숫자
}

class Circle implements Human {
  // `implements` 키워드를 사용하여 해당 클래스가 Human interface 의 조건을 충족하겠다는 것을 명시
  radius: number; // 멤버 변수 radius 값을 설정합니다.
  constructor(radius: number) {
    this.radius = radius;
  }
  //너비를 가져오는 함수를 구현합니다.
  getArea() {
    return this.radius * this.radius * Math.PI;
  }
}

class Rectangle implements Human {
  width: number;
  height: number;
  constructor(width: number, height: number) {
    this.width = width;
    this.height = height;
  }
  getArea() {
    return this.width * this.height;
  }
}

const humanes: Human[] = [new Circle(5), new Rectangle(10, 5)];

humanes.forEach((item) => {
  console.log(item.getArea());
});

콘솔에서 보고싶다면?

  • 코드를 작성하고 yarn build명령어를 입력하고, node dist/practice명령어를 입력하면 node 콘솔 창이 생긴다.
  • typeScript에서는 constructor의 파라미터 쪽에 publicc 또는 private를 사용하면 직접 하나하나 설정해주는 작업을 생략할 수 있다.
//Shape 라는 interface 를 선언합니다.

interface Shape {
  getArea(): number; //Shape interface 에는 getArea 라는 함수가 꼭 있어야 하며 해당 함수의 반환값은 숫자.
}

class Circle implements Shape {
  // implements 키워드를 사용하며 *해당 클래스가 Shape interface 의 조건을 충족*하겠다는 것을 명시합니다.
  constructor(public radius: number) {
    this.radius = radius;
  }
    // 너비를 가져오는 함수를 구현합니다.
    gerArea() {
    return this.radius * this.radius * Math.PI;
  }
}

class Rectangle implements Shape {
  constuctor(private width: number, private height: number) {
    this.width = width;
    this.height = height;
  }
  getArea() {
    return this.width * this.height;
  }
}

const circle = new Circle(5);
const rectangle = new Rectangle(10,5);

console.log(circle.radius); //에러 없이 작동
console.log(ractangle.width); // width 가 private 이기 때문에 에러 발생!

const shapes : Shape[] = [new Circle(5), new Rectangle(10,5)];

shapes.for(shape => {
  console.log('get Area:',shape.getArea());
});

public : 특정 값이 클래스의 코드 밖에서도 조회 가능하다는 것을 의미.

일반 객체를 interface로 타입 설정하기

  • 클래스가 아닌 일반 객체를 interface를 이요하여 타입을 지정하는 방법
interface Person {
  name: string;
  age?: number; // 물음표가 들어가면, 설정을 해도 되고 안해도 되는 값이라는 것을 의미한다.
}
interface Developer {
  name: string;
  age?: number;
  skills: string[];
}

const person: Person = {
  name: '김사람',
  age: 20,
};

const export: Developer = {
  name: '개발자',
  skills: ['js', 'react'],
};
  • 보면 Person과 Developer의 형태가 유사하다. 이럴 땐 interface를 선언 할 때 다른 interfaceextends 해서 상속받을 수 있다.
interface First {
  name: string;
  age?: number;
}
interface Two extends First {
  skills : string[];
}

const first : First = {
  name : '김사람',
  age : 20
}
const two : Two = {
  name : '크크크',
  skills : ['js','re'];
}
const people : Person[] = [first,two];
console.log(people);// [{name:'김사람', age:20}, {name:'크크크',skills:['js','re']}]

Reference : https://velog.io/@velopert/using-react-with-typescript

profile
-기록일지

0개의 댓글