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?

More than 1 year has passed since last update.

Typescript の型エイリアスを override する方法

Posted at

環境

  • typescript - v5.2.2

基本的な型エイリアスの拡張方法

交差型

// 基本とするオプション
type BaseOptions = {
  mode: string;
  ratio: number;
}

// モードパラメタの列挙
type CameraModeEnum = "" | "user" | "environment";

// 拡張したオプション(交差型)
type CameraOptions = BaseOptions & {
  mode: CameraModeEnum;
}; //=> {mode: string | CameraModeEnum, ratio: number }

function getCamera(options:CameraOptions){
  // options は BaseOptions と CameraOptions の両方の特性をもつので string と "" | "user" | "environment" の両方が受け入れ可能
  ...
}

型エイリアス( type ) を拡張させるは、交差させるしか方法がない。
上書き(override)したい。

結論

override みたいな事をする

Omit
// 基本とするオプション
type BaseOptions = {
  mode: string;
  ratio: number;
}

// モードパラメタの列挙
type CameraModeEnum = "" | "user" | "environment";

// 拡張したオプション(交差型)
type CameraOptions = Omit<BaseOptions, "mode"> & {
  mode: CameraModeEnum;
}; //=> {mode: CameraModeEnum, ratio: number }

function getCamera(options:CameraOptions){
  // options は BaseOptions と CameraOptions の両方の特性をもつのが
  // mode プロパティは Omit<> により BaseOptions から消されるので
  //CameraOptions の mode:"" | "user" | "environment" のみが受け入れ可能になる
  ...
}

参考

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?