새벽에 잠 안와서 시작하는 타입스크립트 공부
듣고 있는 강의는 요거 👇
Udemy Understanding TypeScript - 2021 Edition
https://www.udemy.com/course/understanding-typescript
JS위에 더해서 쓰는 언어로 syntax를 더 간단하고 타입을 따로 지정하지않는 js에서 발생하는 에러를 잡기 쉽게해준다. (수학적 더하기를 하는게 아니라 문자로 concatenate를 해버린다던지 하는 오류들)
타입스크립틑 compiling을 하기 전에 개발과정에서만 우리를 도와줄 수 있다. runtime에서는 자바스크립트를 다르게 작동하도록 도와줄 수 없음 (브라우저엔 타입스크립트가 없어서)
자바스크립트에서는 없었던 class, interface, generics 이런 것들을 이용해서 객체지향 프로그래밍을 할 수 있다.
npm install typescript --save-dev
node.js 설치되어있어야함
https://nodejs.org/en/
Visual studio에서 extension으로 TSLint 설치하면 좋음 (ESLint있으면 그것만 써도 됨)
tsc command를 사용하면 ts파일을 compile한다음에 js을 하나 만들어냄
ex. tsc app.ts
localhost실행할때 자동 refresh안되면
npm init
npm install --save-dev lite-server 이거 설치한 다음에
package.json안에 script부분에 "start": "lite-server" 이거 추가해주기
module 이란 import 와 export가 있는 하나의 파일을 말한다.
module is excuted in its own scope.
그렇기때문에 선언하는 변수들은 local이 된다.
default export를 import할때는
export default mutiply
import multiply from '/multiply';
name export를 import할때는
export mutiply
import { multiply } from './multiply';
array 사용법
let list: number[] = [1,2,3];
let list: Array<number> = [1,2,3];
enum = numeric number
enum Color {Red, Green, Blue};
let c: Color = Color.Green;
interface Person {
firstName: string;
lastName: string;
}
-> 하나의 타입으로 선언된거라 사용할때는
function fullName(person: Person) {
} 이런식으로
function isValidPassword(password: string) {
return password.length >= 6
}
isValidPassword(null)
it produce error if the strictNullChecks option is true in the app's tsconfig
function helloWorld() {
console.log('Hello World')
}
이경우에는 type을 void로 하면 된다.
child 컴포넌트를 parent컴포넌트에 상속시키고 싶을떄
class Child extends Parent {}
: 어떤 클래스 혹은 함수에서 사용할 타입을 그 함수나 클래스를 사용할때 결정하는 것.
키워드를 사용하면 제네릭을 사용하겠다는 의미.
class Stack<T> {
private data: T[] = [];
constructor() {}
push(item: T): void {
this.data.push(item);
}
pop(): T {
return this.data.pop();
}
}
사용할때:
const numberStact = new Stack<number>();
any 는 컴포넌트 만들때(function, class) 사용하지 않기. 그 대신에
function find<T>(arr: T[], testFunc: (item: T) => boolean): T | undefined {
이걸로 써준다.
function launch<Player extends CanFly>(player: player) {