[2][Refactor] API로 가져온 Data의 정확한 type 지정

Soly; 독특하게·2021년 3월 14일
1

Lily의 인턴일지

목록 보기
2/6
post-thumbnail

목적 : method,mode... 들의 타입을 정확히 지정하고 싶어요.

BackEnd에서 가져 온 데이터들을 넣을 변수 명들을 선언했다. 이 메서드들은 추상클래스인 RequestInitimplements 한 class Request 에 있다.

  • network.ts
private _method;
private _mode;
private _cache;
private _credentials;
private _headers;
private _body;
private _redirect;
private _referrer;

RequestInit 에는 다음과 같이 각 메서드들의 타입들이 지정되어 있다.

  • lib.dom.d.ts
interface RequestInit {
	body?: BodyInit | null;
	cache?: RequestCache;
...
}

여기서, BodyInit 의 타입을 가져오고 싶으면, 다음과 같이 타입이 정해져 있는 것을 network.ts로 가져와서, export 해와야 한다.

type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream<Uint8Array> | string;

해당 타입을 가져온 후 , export한다

  • network.ts
export type BodyInit =
  | Blob
  | BufferSource
  | FormData
  | URLSearchParams
  | ReadableStream<Uint8Array>
  | string;

그 후에, 타입을 지정해준다.

private _method: Methods;
private _mode: RequestMode;
private _cache: RequestCache;
private _credentials: RequestCredentials;
private _headers: HeadersInit;
private _body: BodyInit | null;
private _redirect: RequestRedirect;
private _referrer: string;

그러면, constructor은 다음과 같다.

특히, python과 비슷하게 파라메타를 순서 없이 가져오기 위해서 지정해주었다.

constructor({
  cache = 'no-cache', 
  body = null,
} = {}) {
  this._cache = cache as RequestCache;
  this._body = body ? JSON.stringify(body) : null;
}

private로 지정해줬기 때문에, getter와 setter를 작성하고 이도 마찬가지로 타입을 지정해준다.

get cache(): RequestCache {
  return this._cache;
}
get body(): BodyInit | null {
  return this._body;
}

set body(body: BodyInit | null) {
  this._body = body;
}
profile
협업을 즐겨하는 목표지향적인, Front-End 개발자입니다.

0개의 댓글