Programming/JavaScript & TypeScript
타입 별칭(Type Alias)
홍열
2022. 2. 16. 16:53
728x90
타입에 다른 이름을 붙여주는것
Interface랑 비슷해 보인다
Primitive, Union Type, Tuple, Function, 기타 직접 작성해야하는 타입을 다른 이름으로 지정할 수 있다.
별명 개념으로 보면 된다.
https://www.digitalocean.com/community/tutorials/typescript-type-alias
How To Use Type Aliases in TypeScript | DigitalOcean
www.digitalocean.com
https://laikhan-workshop.tistory.com/45
[Typescript] Type assertion, Type alias
Type assertion 형변환과는 다르다. '타입이 이것이다' 라고 컴파일러에게 알려주는 것을 의미한다. 문법적으로 두가지 방법이 있다. 변수 as 강제할 타입 (권장) <강제할 타입> 변수 let value: any = "this
laikhan-workshop.tistory.com
// Aliasing Primitive
type MyStringType = string;
const str = "world";
let myStr:MyStringType = "hello"
myStr = str // MyStringType과 string은 같은 타입이기때문에 대입 가능
// Aliasing union
let person:string|number = 0;
person = 'Mark';
type stringOrNumber = string|number;
let another:stringOrNumber = 1
another = 'hong'
// Aliasing Tuple
let personInfo:[string, number] = ['Hong', 33];
type PersonType = [string, number];
let anotherPersonInfo:PersonType = ['Annn', 24]
// Aliasing Function
type EatType = (food:string) => void;
TypeAlias와 interface를 사용하는 기준
타입이 목적, 존재 가치가 명확하면 interface,
대상을 가리키면 typealias 사용
결국 여러 타입을 하나의 타입으로 만들고, 그 안에서 고르면 되는게 타입인것 같다...
유니온을 이용해서...
type UserState = 'PENDING' | 'APPROVED' | 'REJECTED';
function checkUser(user: User2) : UserState {
//유저 상태중에 하나를 리턴하게 만듬
if(user.login()){
return 'APPROVED'
}else{
return 'REJECTED'
}
}
type도 상속이나 구현이 가능하지만, union으로 만들어진 타입에서는 불가능하다.
잘 사용하진 않는다. 그럴바에는 interface를 사용하자
type TypeA = {
str: string;
};
// union type으로 정의된 경우 extends 나 implements 와 사용할 수 없다.
type TypeB = TypeA | {
num: number;
};
class Person implements TypeA {
str: string;
constructor(name:string) {
this.str = name
}
}
interface Person extends TypeB {} /* 오류 */
// An interface can only extend an object type or intersection of object types with statically known members.