728x90
반응형
Type Alias(타입 변수에 담기)
- 대문자로 시작(국룰), 뒤에 Type 붙이기(권장)
type AnimalType = {
name: string;
age: number;
};
let animal: AnimalType = { name: "kim", age: 15 };
// const는 변경 불가능한 변수지만,
// 타입을 오브젝트로 지정하면 득정 키에 대한 값 변경 가능
const birthArea = "seoul";
const birthRegion = { name: "seoul" };
birthRegion.name = "busan";
console.log(birthRegion);
type GirlFriend = {
readonly name: string;
};
const girlFriend: GirlFriend = {
name: "엠버",
};
// 타입에러가 나지만 javascript에서는 정상적으로 동작해준다.
// girlFriend.name = "heesun";
console.log(girlFriend);
&연산자로 object 타입 extend 하기(타입 합치기)
// 타입 합치기
type NameType = string;
type AgeType = number;
type PersonType = NameType | AgeType;
type PositionX = { x: number };
type PositionY = { y: number };
// { x: number, y:number }로 만들고 싶을때 : & 연산자
// & 연산자로 obejct 타입 extend 하기 !
// (참고) 같은 이름의 type 변수 재정의 불가능
type PositionType = PositionX & PositionY;
let position: PositionType = { x: 10, y: 10 };
console.log(position);
interface로 타입선언과 extends
// &
type Animal = { name: string };
type Cat = { age: number } & Animal;
// interface : 유연
// 외부 라이브러리같은 경우 interface를 많이 쓴다.
interface Student {
name: string;
}
interface Teacher {
name: string;
age: number;
}
// 중복선언 가능
// 동일한 변수명은 불가능
interface Teacher {
info: string;
}
interface Principal extends Teacher {
birthDate: number;
}
728x90
반응형
'Web > Typescript' 카테고리의 다른 글
[Typescript]함수와 메소드에 type alias 지정 (0) | 2022.06.12 |
---|---|
[Typescript]Literal Type로 만드는 const 변수 유사품 (0) | 2022.06.11 |
[Typescript]타입을 미리 정하기 애매할 때 & 타입지정 & Narrowing (0) | 2022.06.11 |
[Typescript]컴파일시 세부설정(tsconfig.json) (0) | 2022.06.11 |
[Typescript]설치셋팅&기본문법 (0) | 2022.06.11 |