타입스크립트 - 타입

이라운·2022년 9월 7일
1
post-thumbnail

왜 Typescript 를 사용하는가?

브라우저는 Typescript 를 이해하지 못하기 때문에 JS 로 변환해줘야 한다. 이런 과정을 거쳐야 함에도 Typescript 가 각광을 받는 이유는 아래의 코드를 보면 알 수 있다.

JS는 동적언어로서 런타임에 타입을 결정하기 때문에, 에러를 잡아줄 수 없다.
반대로 Typescript 또는 Java 와 같은 정적언어는 컴파일 단계에서 타입을 결정하기 때문에 에러를 잡아낼 수 있다.

Typescript 기본 타입

공식문서 - 기본 타입

기초요소

string, number, boolean

배열

Array<number> === number[]

any

말그대로 '어떤 것이든'가능하게 한다. 지지고 볶고 난리쳐도 에러를 발생시키지 않는다.

let obj: any = { x: 0 };
// None of the following lines of code will throw compiler errors.
// Using `any` disables all further type checking, and it is assumed 
// you know the environment better than TypeScript.
obj.foo();
obj();
obj.bar = 100;
obj = "hello";
const n: number = obj;

변수에 대한 Annotation

let myName: string = "Alice";
// Annotation 을 달아주지 않아도 바로 타입 추론이 가능하다. 
let myName = "Alice";

함수의 타입

매개변수

// Parameter type annotation
function greet(name: string) {
  console.log("Hello, " + name.toUpperCase() + "!!");
}

return 타입

function getFavoriteNumber(): number {
  return 26;
}

Anonymous 함수

// No type annotations here, but TypeScript can spot the bug
const names = ["Alice", "Bob", "Eve"];
 
// Contextual typing for function
names.forEach(function (s) {
  console.log(s.toUppercase());
// Property 'toUppercase' does not exist on type 'string'. Did you mean 'toUpperCase'?
});
 
// Contextual typing also applies to arrow functions
names.forEach((s) => {
  console.log(s.toUppercase());
// Property 'toUppercase' does not exist on type 'string'. Did you mean 'toUpperCase'?
});

객체

// The parameter's type annotation is an object type
function printCoord(pt: { x: number; y: number }) {
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 3, y: 7 });

있어도 되고 없어도 되고

? 을 쓰면 되는데, 무조건 필수 매개변수 뒤에서 사용되어야 한다.

function printName(obj: { first: string; last?: string }) {
  // ...
}
// Both OK
printName({ first: "Bob" });
printName({ first: "Alice", last: "Alisson" });

Union 타입

타입을 여러가지를 허용하도록 할 수 있다.

function printId(id: number | string) {
  console.log("Your ID is: " + id);
}
// OK
printId(101);
// OK
printId("202");
// Error
printId({ myID: 22342 });
// Argument of type '{ myID: number; }' is not assignable to parameter of type 'string | number'.

Interface

interface User{
	name :string,
	age :number
}
let user :User={
	name : 'mj',
	age :20
}
user.age = 10; //user안에 age수정 가능
user.gender = 'f' //오류(interface User에 gender을 넣어도 let user에 안써두면 오류)

constructor

class Bmw implements Car{
	wheels;
	color = 'red';
	constructor(c :number){
		this.wheels = c
	}
	start(){
		console.log('go...'}
	}
}
const b= new Bmw(4)
b.start(); //'go...'
profile
Programmer + Poet = Proet

0개의 댓글