0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeScript型のtips

Posted at

空オブジェクト

export type EmptyObject = Record<string, never>;

Anyオブジェクト

export type AnyObject = Record<string, unknown>;

オブジェクトのvalueのunion type

/**
 * @example
 * type Obj =  {
 *   x: string;
 *   y: number;
 * };
 * ValuesType<Obj>; // string | number
 */
export type ValuesType<T extends AnyObject> = T[keyof T];

Arrayのelementの型

/**
 * @example
 * type Element = ArrayElement<string[]>;
 * // string
 */
export type ArrayElement<ArrayType extends readonly unknown[]> = ArrayType extends readonly (infer ElementType)[]
  ? ElementType
  : never;

配列の要素かどうかを判定する

export const isArrayElement = <T>(array: T[], value: any): value is T => {
  return array.includes(value);
};

オブジェクトであるか

export const isObject = (value: unknown): value is Record<string, unknown> => {
  return Object.prototype.toString.call(value).slice(8, -1) === 'Object';
};

keyがobjのキーであるか

/**
 *
 * @example
 * const obj =  {
 *   x: 1;
 *   y: 2;
 * } as const;
 * const key: string = '';
 * if (isKeyOf(key, obj)) {
 *   // key is "x" | "y"
 * }
 * // key is string
 */
export const isKeyOf = <T extends object>(key: keyof any, obj: T): key is keyof T => {
  return key in obj;
};

オブジェクトのキーを取得する

export const getKeys = <T extends Record<string, unknown>>(obj: T): (keyof T)[] => {
  return Object.keys(obj);
};

一部プロパティをオプショナルに変更する

export type MarkOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;

全てのプロパティをNullableに変更する

export type NonNullableProperties<T> = {
  [K in keyof T]: NonNullable<T[K]>;
};

一部のプロパティをNullableに変更する

export type MarkNonNullable<T, K extends keyof T> = Omit<T, K> & NonNullableProperties<Pick<T, K>>;

参考記事

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?