[F-Lab 모각코 챌린지 - 59일차] - typescript

Big One·2023년 7월 8일
0

F-Lab

목록 보기
32/69

enum, keyof, typeof

enum 은 위에서부터 순서대로 0, 1, 2, .. 값이 배정된다. 임의로 설정할 수도 있고 특정 값만 설정할 수 있다.

여러 변수들을 하나의 그룹으로 묶고싶을 때 사용한다.

const enum EDirection {
	Up,  //0
	Down, //1
	Right, //2
	Left,  //3
}
const a: EDirection = 0;
const walk: (dir: EDirection) = (dir) => {}

const ODirection = {
	Up: 0,
	Down: 1,
	Right: 2,
	Left: 3,
};

이렇게 타입으로 enum 을 사용할 수 있다. enum 말고도 객체로 해도 무방하다.

keyof 는 키 값들을 나타내주는 것이고, typeof 는 타입으로 사용하겠다라고 지정하는 것이다.

위 코드 중 ODirection 은 객체이므로 타입으로 사용하려면 typeof를 사용하여야하고 key값이 필요한 경우 keyof를 사용하고 value값이 필요하면 어떤 조합이 필요한지 코드로 확인해보겠다.

const ODirection = {
	Up: 0,
	Down: 1,
	Right: 2,
	Left: 3,
};

// ODirection 객체의 키들만 나옴 Up | Down | Right | Left
type Key = keyof typeof ODirection;
const keyEx: Key = 'Up';

// ODirection 객체의 값들은 0 | 1 | 2 | 3
const Direction = typeof ODirection[keyof typeof ODirection]
// keyof typeof ODirection 으로 키를 구한 것(key)에 ODirection[key] 하면
// 값이 나오게되니 .. 그 후 타입으로 사용하겠다 이 말이다!!

union( | ), intersection( & )

일반 원시값일때와 .. 객체일 경우가 굉장히 다른데 잘 보셈!

type Add = number & string ; // 이건 말이 안된다 그러므로 never타입이 됨.
type Person = { name: string } & { age: number }

// intersection(&) 사용시 and, && 와 같이 모든 타입의 조건이 들어가야한다.
const person: Pesrson = { name: 'BigOne', age: 18} 

// union(|) 사용시 or , || 과 같이 하나만 만족해도 된다.
const person2: Person2 = { name: 'BigOne' }

타입 애일리어스(type) 과 인터페이스의 상속(extends)

type과 interface의 차이점이 몇 가지 존재하고 두 개가 전혀 다른 분리된 타입 정의방법은 아니다.

type 에 interface를 상속할 수 있고 interface에 type을 상속할 수도 있다.

type Animal = { breath: true };
type Poyouru = Animal & { breed: true };
type Person = Poyouru & { think: true };

const bigOne: Person = { breath: true, breed: true, think: true };

interface A {
	eat: true;
}
interface B extends A {
	bark: true
}

const sujung: B = { eat: true, bark: true };

interface AA {
	id: number,
}
interface AA {
	name: string,
}
interface AA {
	age: number,
}

const cristal: AA = { id: 1, name: cristal, age: 3 };

interface MixedTI extends Person, AA{
	sayHi: string,
}

type 은 interface 처럼 재 정의가 안된다. interface 는 자바에서 오버 라이딩처럼 재정의해서 사용할 수 있고 상속도 가능하다. type 도 & 를 통해 상속? 느낌으로 가능하지만 interface를 좀 더 지향하는 편이다.

profile
이번생은 개발자

0개의 댓글