TypeScript👀
let isWinter : boolean = false;
let count : Number = 5 ;
let name : String = "Joanne" ;
//any는 Dynamic Typing을 가능하게 함
let names : any[] = ["Joanne","Jake","Judy",5]
//array의 경우 아래 두 가지 방법으로 적용 가능
//리터럴을 적용한 방식
let list : number[] = [1,2,3]
//제네릭을 이용한 방식
let list : Array<number> = [1,2,3]
선언 되지 않은 변수가 undefined 이고, 선언 되 었지만 현재 값은 없는 것 이 null 이다.
Something hasn't been initialized : undefined.
Something is currently unavailable: null.
마이크로 소프트에 따르면 null을 사용하지 말고 undefined만 사용하라고 함! microsoft github
let users : [number,string] = [1, 'one']
객체형태에서 요소들의 번호를 매길 수 있고 기본은 0으로 시작하지만 1로 지정해주면 1부터 시작하게 바꿀 수 도 있고, 지정 해 줄 수도 있다.
enum Color {
Red = 2
Green = 4
Blue = 6
}
let a : Color = Color.Green;
console.log(a)
//했을때 4 가 출력된다
어떠한 타입도 존재할 수 없음을 나타내며 any의 반대 타입이다. void는 함수에서 반환값이 없을때 반환 타입을 표현하기 위해 쓰인다.일반 변수에 선언하기에 옳지 않다.
function warnUser() : void {
console.log("This is my warning message")
}
브라우저는 오직 JavaScript 만 읽을 수 있기 때문에 TypeScript를 JavaScript로 compile하는 과정이 필요하다.
먼저 typerscript파일을 만들고 tsc 파일을 만들면 js파일을 만들어 준다
type을 정의해주는 두 가지 방법으로는 interface와 type이 있다.
Interface와 type을 비교한 stackOverflow
Interface와 type을 비교한 블로그
interface Coffee {
name : string;
}
interface Coffee {
price : number;
}
const coffee: Coffee = {
name : "Americano",
price: 4100
}
interface Person {
firstName : string;
lastName : string;
}
function greeter(person: Person) {
return "Hello, " + person.firstName + " " + person.lastName;
}
let user = { firstName: "Joanne", lastName: "Kim" };
interface IEmployee {
empCode: number;
empName: string;
getSalary: (number) => number; // arrow function
getManagerName(number): string;
}
-type 또한 특정 타입에 별칭을 붙이는 용도로 사용 되고, TypeScript가 mature되면서 점점 feature가 비슷해 지고 있다.
-Union types with primitives Type끼리는 merge가 불가능해서 intersection 사용해야 함
출처 블로그
https://velog.io/@velopert/typescript-basics
타입스크립트를 사용하는 리액트 컴포넌트는 이와 같이 *.tsx 확장자를 사용
type을 정의해주는 두 가지 방법으로는 interface 와 type이 있다.
state와 action을 parameter로 받아서 state를 업데이트 하고, function을 호출할 때, state, dispatch를 통해서 각각의 변경된 state를 관리해준다.
action에 대한 타입스크립트 타입을 준비하고 “ |”(union) 을 사용해서 결합시킨다.
TypeScript환경에서 useReducer를 쓰면 자동완성이 잘 되고 타입체킹도 잘 된다.