타입 스크립트 - 기본

김동규·2022년 10월 31일
0

타입스크립트

목록 보기
1/3

타입스크립트는 왜 사용하는가?

  • 런타임 이전 코딩 단계에서 에러를 발견할 수 있으며 에러메세지가 보다 상세하다.
  • 자바스크립트에서는 타입을 알 수 없어 에디터가 제공하지 못했던 자동완성 기능을 제공한다.

타입스크립트의 타입

const str: string = '1';
const num: number = 1;
const anything: any = 1 | '1' | true | [];
const bool: boolean = true | false;
const nullValue: null = null;
const undefinedValue: undefined = undefined;

// 객체형

// array 안에 포함될 타입도 지정 가능하다
const array: number[] = [1,2,3,4];
// Generics: 후술
const array2: Array<number> = [1,2,3];

// Tuple : 배열의 길이가 고정되고 각 요소의 타입까지 지정되어 있는 자료형이다.
const tuple_arr: [string, number] = ['hello', 3];

// Enum : 열거형, 상수값의 집합을 뜻한다. 자세한 내용은 후술
// index로 접근 가능하며, 변경 가능하다
enum friendsEnum { kim = 1, seo, choi};
let person:friendsEnum = friendsEnum.kim;
let person2:friendsEnum = friendsEnum[1];

// void : null, undefined. 함수 반환값이 없는 경우에도 할당
const voidValue: void = null | undefined;

function hello (): void{
	console.log("hello world")
};

// never : 실행되지 않는다. 항상 오류를 발생시키거나 절대 반환하지 않는 반환타입으로 쓰인다.
function helloNot (): never{
  	// console.log("hello world"); 작동되지 않음
  	return error("뭔가 이상해");
};

interface는 뭐지?

interface는 instance를 생성하지 않고 다만 객체의 형태만을 미리 정의해두는 키워드다.

// 어떤 객체를 선언할 때, 안에 포함될 property의 형태를 일일히 입력하기는 번거롭다.
const user1: {name: string, age: number} = {
	name : "Jack",
  	age : 23
}

// 이럴 때 인터페이스를 사용하면 형태를 편하게 지정할 수 있다.
// 기본적으로 interface의 형태는 객체와 비슷하다.

interface UserInterface {
	name: string;
  	// ?를 통해 optional로 지정 가능하다.
 	age?: number;
  	// string index signatuer
  	[propName: string]: any;
}}


const user2: UserInterface = {
	name : "John",
	age : 33
}


// clsss, function의 argument와 return 값에도 사용 가능하다
class UserAccount {
	name: string;
  	age: number;
  
  	constructor(name, age){
    	this.name = name;
      	this.age = age;
    }
}

const user3: UserInterface = new UserAccount("Jenny", 21);

function deleteUser(user: UserInterface){
	//...
}

function getUser(): UserInterface{
	//...
}

interface와 type키워드의 차이는?

type키워드는 type alias를 위해 만들어졌고 interface는 객체의 명세를 지정하기 위해 만들어졌다.

// string 같은 넓은 범위의 값이 아니라 일정 범위 내로 한정지을 수 있으며
type Animal = "bird" | "dog" | "cat";

// 객체를 정의할 수도 있다.
type Person = {
	height: number,
  	weight: number
}

interface와 type은 여러 특징을 공유하기 때문에 솔직히 글로 이해하는 것보다 직접 사용해보며 용례를 파악하는 편이 도움이 될 것같지만, 사용법에 대한 몇 가지 지침을 발견할 수 있었다.

Differences Between Type Aliases and Interfaces

Type aliases and interfaces are very similar, and in many cases you can choose between them freely. Almost all features of an interface are available in type, the key distinction is that a type cannot be re-opened to add new properties vs an interface which is always extendable.

type키워드로는 같은 이름으로 중복해 선언할 수 없다. interface의 경우 같은 이름으로 중복 선언할 경우 내부의 property가 추가된다.

React TypeScript Cheatsheets 커뮤니티에서는 다음과 같은 글이 남겨져 있다.

Types or Interfaces?

  • Use Interface until You Need Type
  • always use interface for public API's definition when authoring a library or 3rd party ambient type definitions, as this allows a consumer to extend them via declaration merging if some definitions are missing.
  • consider using type for your React Component Props and State, for consistency and because it is more constrained.

차이점을 확신할 수 없기에 차후 내용을 추가하거나 별도의 주제로 다루어야 할 것 같다.

profile
공식문서를 사랑하는 프론트엔드 주니어 개발자

0개의 댓글