객체의 key 값에 유니온 타입 선언하기

1
2
3
4
5
type userInfoType = "name" | "age" | "address";

interface User {
[key: userInfoType]: string;
}

유니온 타입 에러

  • “인덱스 시그니처 매개변수는 리터럴 타입이나 제네릭 타입이 될 수 없다.”는 에러가 발생했다.
  • 매핑된 객체를 대신 사용하라고 알려준다.

해결방법

1
2
3
4
5
6
7
8
9
10
11
type userInfoType = "name" | "age" | "address";

type userType = {
[key in userInfoType]: string;
};

let user: userType = {
name: "홍길동",
age: "20",
address: "서울",
};

댓글 공유

Omit<T,K> 타입

1
2
3
4
5
6
7
8
9
10
11
interfact Todo {
title:string;
description:string;
completed:boolean;
}

type TodoPreview = MyOmit<Todo, 'description' | 'title'>

const todo: TodoPreview {
completed:false
}
  • TypeScript Omit타입은 해당 객체 타입에서 Key 타입을 제외할 때 사용한다.

댓글 공유

📌 Literal Type

타입 지정시 string, number 같은 원시타입만 할당할 수 있는 것이 아니다.

개발자가 지정한 글자나 숫자 들을 타입으로 지정할 수 있다.

1
2
let john: "Texas";
let kim: 33;
  • 이제 john에는 ‘Texas’라는 글자만 할당될 수 있고 kim에는 33이라는 숫자만 할당될 수 있다.
계속 읽기

📌 type alias(타입별칭)

1
type Animal = string | number;
  • type 타입변수명 = 타입종류
  • 이런 식으로 타입 별칭으로 변수처럼 담아서 재사용할 수 있다.
  • 관습적으로 대문자 사용

🏓 function type 지정하기

1
2
3
4
5
6
7
8
9
type NumOut = (x: number, y: number) => number;

let ABC: NumOut = function (x, y) {
return x + y;
};
function removeDash(x: string): number {
let result = x.replace(/-/g, "");
return parseFloat(result);
}
계속 읽기

📌 TypeScript와 JavaScript 관계

모든 JavaScript는 TypeScript이지만, 모든 TypeScript가 JavaScript는 아니다.

1
2
3
4
5
6
7
8
9
10
interface State {
name: string;
capital: string;
}
const states: State[] = [
{ name: "yiju", capital: "경기도" },
{ name: "kim", capitol: "서울" },
]; // Error
// Type '{ name: string; capitol: string; }' is not assignable to type 'State'.
// Object literal may only specify known properties, but 'capitol' does not exist in type 'State'. Did you mean to write 'capital'?

위 예시를 설명하면, 앞서 말한 모든 타입스크립트가 자바스크립트다 라고 하는 말은 틀렸다.

계속 읽기

📌 타입스크립트란?

JavaScript는 동적 타입만을 제공하여 예측하기 어려운 타입변환으로 디버깅이 어려워지는 문제점이 있어 이를 해결하고자 TypeScript가 탄생하였다.

TypeScript는 정적 타입 시스템을 사용하여 코드가 실행되기 전에 코드에 대하여 예측해준다.

계속 읽기
  • page 1 of 1

loco9939

author.bio


author.job