7
1

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 3 years have passed since last update.

TypescriptでExact(完全一致)を実現する方法

Last updated at Posted at 2019-12-13

型が完全一致しないとエラーにする方法です。
そこで、以下のようなExactというGenericを定義して使います。

type Exact<T, R> = T extends R
  ? R extends T
    ? T
    : never
  : never

type Base = {
  b: number
}

type Derived = Base & {
  d: number
}

function baseFunc(base: Base) {}
function exactBaseFunc<T = Base>(b: Exact<T, Base>) {}

const base: Base = { b: 1 }
const derived: Derived = { b: 1, d: 2 }

baseFunc(base)          // ok
baseFunc(derived)       // ok
exactBaseFunc(base)     // ok
exactBaseFunc(derived)  // error

補足ですが、派生の型に基本の型を入れるとエラーになります。

function derivedFunc(derived: Derived) {}
derivedFunc(base)       // error
derivedFunc(derived)    // ok

APIやストレージなど、特定のプロパティしか保存したくないという時にこのようにしておくと型でエラーが出るので安心。

7
1
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
7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?