[typescript] 등록 | 수정 파라미터 타입 다를 경우 정의하는 방법

Darcy Daeseok YU ·2023년 7월 11일
0

등록시 필수값 id는 필수값이 아니다.
autoIncrement인 경우가 많음.

등록 시 필수값 아님
interface insertParams {
id?: number;
...
}

업데이트 시 : 필수
interface updateParams {
id: number;
...
}


interface UserProfile {
  id: number;
  username: string;
  email: string;
  profilePhotoUrl: number;
}

// 등록 시 이메일은 필수값이다. id는 아직 생성되지 않앗다.
type TInsertEssentialPickKeys = keyof Pick<UserProfile, "email">;
type TInsertOptionalPickKeys = keyof Omit<UserProfile, "email ">;

type TInsertEssential = {
  [p in TInsertEssentialPickKeys]: UserProfile[p];
};
type TInsertOptional = {
  [p in TInsertOptionalPickKeys]?: UserProfile[p];
};

type TInsertUserParams = TInsertEssential & TInsertOptional;

type keys = "email" | "id";

// 등록된 후 id는 pk값으로 사용된다. email값도 필수값
type TUpdateEssentialPickKeys = keyof Pick<UserProfile, keys>;
type TUpdateOptionalPickKeys = keyof Omit<UserProfile, keys>;

type TUpdateEssential = {
  [p in TUpdateEssentialPickKeys]: UserProfile[p];
};
type TUpdateOptional = {
  [p in TUpdateOptionalPickKeys]?: UserProfile[p];
};

type TUpdateUserParams = TUpdateEssential & TUpdateOptional;
profile
React, React-Native https://darcyu83.netlify.app/

0개의 댓글