Typescript
타입만 써도 개이득(TODO)
https://www.youtube.com/watch?v=ViS8DLd6o-E&list=WL&index=8&t=117s
yarn으로 설치하고
yarn init으로 프로젝트 만든뒤에
index.ts를 만들고
tsconfig.json 파일만들어서
{
“compilerOptions”: {
“module”: “CommonJS”,
“target”: “ES2015”,
“sourceMap”: true
},
“include”: [“index.ts”],
“exclude”: [“node_modules”]
}
이런식으로 설정파일을 만들어준다.
컴파일은 아래 사진처럼
tsc라고 치면 경로의 ts가 js로 컴파일된다
대표사진 삭제
사진 설명을 입력하세요.
이것을 이요ㅗㅇ해서
package.json에서 스크립트도 작성해보자
{
“script”: {
“start”: “node index.js”,
“prestart”: “tsc”
}
}
js로 먼저 컴파일 한 후 nodejs로 실행하는 스크립트이다
const name = ‘Hoo’,
age = 24,
gender = ‘male’;
const sayHi = (name, age, gender?) => { // 물음표
console.log(Hello ${name}, you are ${age}, you are a ${gender}
);
};
sayHi(name, age);
export {};
물음표가 없으면 타입스크립트에서는 아규먼트가 하나 적어서 컴파일도 안된다.
하지만 물음표를 붙이면 선택적인 파라메터가 된다.
자바스크립트는 그딴거없이 다 됐다는게 중요하다
https://darrengwon.tistory.com/116
이미지 썸네일 삭제
tsc-watch 사용하기
https://www.npmjs.com/package/tsc-watch tsc-watch The TypeScript compiler with onSuccess command www.npmjs.com 단도직입적으로 tsc-watch를 왜 사용하느냐 => nodemon과 같이 자동 실행을 해주기 때문이다…
darrengwon.tistory.com
interface Human {
name: string;
age: number;
gender: string;
}
const person = {
name: ‘asdf’,
gender: ‘sadf’,
age: 24,
};
const sayHi = (person: Human): number => {
console.log(
Hello ${person.name}, you are ${person.age}, you are a ${person.gender}
);
return 0;
};
console.log(sayHi(person));
export {};
interface라는게 추가되었다.
person이 human 타입인지를 타입스크립트가 검사해줄 수 있게 되었다.
“use strict”;
Object.defineProperty(exports, “__esModule”, { value: true });
const person = {
name: ‘asdf’,
gender: ‘sadf’,
age: 24,
};
const sayHi = (person) => {
console.log(Hello ${name}, you are ${age}, you are a ${gender}
);
return 0;
};
console.log(sayHi(person));
//# sourceMappingURL=index.js.map
빌드된 자바스크립트 코드를 보면 인터페이스는 사라져있다.
class Human {
public name: string;
public age: number;
public gender: string;
private accessTest: boolean;
constructor(name: string, age: number, gender: string) {
this.name = name;
this.age = age;
this.gender = gender;
this.accessTest = true;
}
}
const hoo = new Human(‘hoo’, 24, ‘male’);
const sayHi = (person: Human): number => {
console.log(
Hello ${person.name}, you are ${person.age}, you are a ${person.gender}
);
return 0;
};
console.log(sayHi(hoo));
export {};
클래스도 있는데 중요한점은 접근지정자가 있다!!!!
이제 씨플플처럼 객체지향프로그래밍이 제대로 가능할것도 같다.
“use strict”;
Object.defineProperty(exports, “__esModule”, { value: true });
class Human {
constructor(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
}
const hoo = new Human(‘hoo’, 24, ‘male’);
const sayHi = (person) => {
console.log(Hello ${person.name}, you are ${person.age}, you are a ${person.gender}
);
return 0;
};
console.log(sayHi(hoo));
//# sourceMappingURL=index.js.map
ES6부터 클래스가 있기때문에 빌드해도 JS에 클래스는 남는다.
접근지정자는 없어졌지만
interface Pointlike {
x: number;
y: number;
}
interface Named {
name: string;
}
function printPoint(point: Pointlike) {
console.log(“x = “ + point.x + “, y = “ + point.y);
}
function printName(x: Named) {
console.log(“Hello, “ + x.name);
}
const obj = {
x: 0,
y: 0,
name: “Origin”,
};
printPoint(obj); // ?
printName(obj); // ?
C++ 같은 엄격한 타입을 생각하면 마지막 함수호출이 이해가 가지 않을 수 있다.
핸드북에서도 설명하듯,
파라메터로 받는 오브젝트는 베이스 클래스이고,
아규먼트로 파생 클래스를 넣는다고 생각하고 마음을 해결하자.
이건 이상한건 아니고 덕타이핑이라는거다.
꽥꽥하면 오리로 보는거지(동작이지만)
형태를 보고 타입을 파악하는게 타입스크립트의 정책이다.
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig): { color: string; area: number } {
return { color: config.color || “red”, area: config.width ? config.width*config.width : 20 };
}
인터페이스에 ?로 옵셔널 필드도 있을 수 있다.
위와 마찬가지로 덕타이핑에 의해 없을수도 ㅇㅣㅆ따.
interface Point {
readonly x: number;
readonly y: number;
}
let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray
ro[0] = 12; // error!
readonly도 가능하다
자바처럼 인터페이스의 계약조건을 구현하는것도 아래처럼 가능하다.
굳이 인터페이스라는게 생겨난다는걸 생각해보면 활용해볼만한다.
interface ClockInterface {
currentTime: Date;
setTime(d: Date): void;
}
class Clock implements ClockInterface {
currentTime: Date = new Date();
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) {}
}
class Point {
x: number;
y: number;
}
interface Point3dextends {
Point z: number;
}
클래스는 인터페이스를 대신해서 사용할수도 있다.(당연하지!)
위처럼 상속안해도 쓸수있을거같은데써보자