yarn global add typescript
그 다음에 명령어를 이용하여 tsconfig.json파일을 자동 생성하자.
npx tsc --init
명령어로 생성된 tsconfig.json 안에 outDir
속성을 추가하자.
{
"compilerOptions": {
"target": "ES2015",
"module": "commonjs",
"strict" : true,
"outDir": "./dist"
"esMouleInterop":true
}
}
const message: string = 'hello world';
: string
이라는 코드는 해당 상수 값이 문자열이라는 것을 명시해준다.
tsc
명령어를 입력하고 입력이 되면 js파일이 생성된다.$ 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를 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 콘솔 창이 생긴다.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 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'],
};
interface
를 선언 할 때 다른 interface
를 extends
해서 상속받을 수 있다.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