객체의 속성과 타입을 정의

interface Student{
    korean: number;
    english: number;
    math: number;
}

 

 

이제 Student 를 이용해서 객체(object)를 생성

const joey: Student ={
    korean: 90,
    english: 100,
    math: 80,
}

 

90점 이상인 과목이 몇개 인지 확인

const countOverNinetyScore = Object.values(joey).filter(score => score>90).length;

 

이제부터 오류가 시작된다....

에러 1. Object.values 는 "es2017" 이후 부터 적용되는 문법이여서 에러 발생

 

keys 를 사용하여 변경!

const countOverNinetyScore = Object.keys(joey).filter(key => joey[key] >= 90).length;

 

에러 2. key 가 뭔데??? any 타입일 수도 있는데  막쓰면 안된다는 내용의 에러발생

TSError: ⨯ Unable to compile TypeScript:
- error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Student'.
No index signature with a parameter of type 'string' was found on type 'Student'.
       joey [key]>= 90).length

..... 

 

구글링을 통하여 해결법 발견

const countOverNinetyScore = Object.keys(joey).filter(key 
					=> joey[key as keyof Student]>= 90).length

 

위 코드에서 "joey[ key as keyof Student]" 을 사용하는 이유
key가 Student 인터페이스에서 유효한 키임을 TypeScript 컴파일러에 알려줘야 하기 때문이다.
그냥 joey[key] 를 사용하면 TypeScript 컴파일러는 key 가 Student 인터페이스의
모든 가능한 키 중 하나라는 것을 보장할 수 없으므로 타입 체킹 오류를 발생시킨다.

'프로그래밍 > TypeScript' 카테고리의 다른 글

[ TS ] Promise<void> 의미  (0) 2024.05.07
[ TS ] 상속 : extends, super(),  (0) 2024.05.05
[TS] 유틸리티 타입 (Utility Types): Keyof, Partial  (0) 2024.03.08
[TS] 제네릭 ( Generics )  (0) 2024.03.08
[ TS ] 추상 class  (0) 2024.03.08

 

 

nest 설정

$ npm i -g @nestjs/cli
$ nest new project-name

 

project-name 디렉터리로 가서

$ npm run start:dev

     - 이 모드로 실행을 하면 자동으로 코드수정을 감지하여 반영

 

 

http://localhost:3000/ 로 접속해서 "Hello World!" 가 뜨면 서버 실행 성공

 

참고자료:

https://docs.nestjs.com/first-steps

권한 설정

Npm 의 디렉토리 위치 찾기

$ npm config get prefix

 

출력이 "/usr/local"  이면 아래 명령어를 실행하여 권한을 설정

$ sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}

  - lib/node_modules,bin,share  <- 이 부분은 원하는 폴더로 변경가능

   >> $ sudo chown -R root:$(whoami) /usr/local/lib/node_modules/

추가로 가능한 권한을 설정해 줄 수 있다.

sudo chmod -R 775 /usr/local/lib/node_modules/

775에 대한 내용은 여기 참고 

nest 설치

 

$ npm i -g @nestjs/cli # Nest 프로젝트를 간편하게 생성할 수 있게 도와주는 라이브러리
$ nest new my-web-server # my-web-server(프로젝트 이름)이라는 이름으로 Nest 프로젝트를 생성

 

 

참고자료

https://stackoverflow.com/questions/47252451/permission-denied-when-installing-npm-modules-in-osx

 

Permission denied when installing npm modules in OSX

I'm trying to install node-g.raphael, and I'm getting the following error: Bender-03:htdocs alfred$ sudo npm install node-g.raphael --save Password: > contextify@0.1.15 install /Users/alfred/

stackoverflow.com

https://docs.nestjs.com/first-steps

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

https://stackoverflow.com/questions/49679808/error-eacces-permission-denied-mkdir-usr-local-lib-node-modules-node-sass-b

'프로그래밍 > Nest.js' 카테고리의 다른 글

[ NestJS ] Providers  (0) 2024.04.18
[NestJS] TypeORM 설정방법  (0) 2024.04.17
[ NestJS] DTO?  (0) 2024.04.17
[ NestJS ] Controllers  (0) 2024.04.15
[ NestJS ] 시작하기  (0) 2024.04.15

 

프론트 엔드에서 다른 요청은 다 작동하였는데 딱 한 가지


에러 메세지
"PATCH
http://localhost:63342/localhost:3000/stations/17
404 (Not Found)"

에러 발생 코드
`http:/${IP_ADDRESS}:3000/stations/${id}`

 

이 부분만 오류가 발생... 

 

포스트맨 이용해서 테스트한 결과 백엔드는 문제 없음을 확인

한참을  조사하다가 ... 

작동이되는 코드를 복사/붙여넣기하다가 찾은 에러

http:/ 에 "/" 이 빠졌다...

 

에러 메세지에서 주소를 못 찾는다는 말이 나왔을때 주소와 관련 된 부분을 집중적으로 먼저 확인하자!!

 

비슷 한 로직의 다른 코드들은 정상적으로 작동하는데 하나만 에러가 발생 할 때는

1. 에러 메세지를 확인 후 잘 못된 내용을 가정 먼저 확인

2. 에러 메세지에서 가리키는 부분에서 관련 로직 확인

3. 정상적으로 작동하는 코드와 비교

 

이 순서로 에러를 확인해보자..

 

Keyof : 인터페이스의 키를 반환하여 준다. 

interface User{
   id: number
   name: string;
   age: number;
   gender: "m" | "f";
}

// interface 의 키 부분만 반환
type UserKey = keyof User; // id | name | age | gender

const uk:UserKey = "id"
const uk2:UserKey = "" // 에러

 

Partial<T> : 모든 프로퍼티를 선택사항으로 바꾸어준다.

interface User{
   id: number
   name: string;
   age: number;
   gender: "m" | "f";
}

let admin: Partial<User> = {
   id: 1,
   name: "Bob"
}

/*
위의 admin 은 아래와 같다.
interface User{
   id?: number
   name?: string;
   age?: number;
   gender?: "m" | "f";
}
*/

 

Required<T> : 모든 프로퍼티를 필수 사항으로 바꾸어준다.

ReadOnly<T> : 모든 프로퍼티를 읽기 전용으로 변경해 준다.

 

Record<K, T> : 모든 프로퍼티를 필수 사항으로 바꾸어준다.

const score: Record<"1" | "2" | "3" | "4", "A" | "B" | "C" | "D" | "F"> = {
   1: "A",
   2: "B",
   3: "C",
   4: "D",
}

type Grade = "1" | "2" | "3" | "4";
type Score = "A" | "B" | "C" | "D" | "F";

const score2: Record<Grade, Score> = {
   1: "A",
   2: "B",
   3: "C",
   4: "D",
}

 

interface User{
   id: number
   name: string;
   age: number;
}

function isValid(user:User){
   const result : Record<keyof User, boolean> ={
      id : user.id > 0,
      name : user.name !== "",
      age : user.age > 0 
   }
   return result;
}

 

 

Pick<T, K>: 인터페이스에서 원하는 프로퍼티를 선택

Omit<Type, K>

 

Exclude<T1, T2> T1에서 T2를 제외

 

NonNullable<Type>

type T1 = string | null | undefined | void;
type T2 = NoNullable<T1> // string | void

 

'프로그래밍 > TypeScript' 카테고리의 다른 글

[ TS ] 상속 : extends, super(),  (0) 2024.05.05
[ TS ] interface : 필터링하기  (0) 2024.04.01
[TS] 제네릭 ( Generics )  (0) 2024.03.08
[ TS ] 추상 class  (0) 2024.03.08
[TS] Class : Constructor(생성자) & Access Modifiers  (0) 2024.03.08

+ Recent posts