LoginSignup
7
4

More than 5 years have passed since last update.

TypeScriptで型のオーバーライドをしたい

Last updated at Posted at 2017-09-10

spread operator

interface Tweet{
  id:string;
  user:string;
  body:string;
}

//tweetはTweet型、userはUser型とする
let tw={...tweet,...{user:user}};

この時の変数twの型を定義したい時どうしますか?
素直に書いてみましょう

interface Tweet2{
  id:string;
  user:User;
  body:string;
}

面倒ですね。プロパティが増えるともっと大変です。

typelevel-ts

typelevel-tsという便利なライブラリがあります。
このライブラリを使うとこう書けます。

import {ObjectOverwrite} from 'typelevel-ts';
type Tweet2=ObjectOverwrite<Tweet,{user:User}>;

これだけです。

他のライブラリ

  • type-zoo
  • typical

というライブラリもあります。

中身を読んでみる

Conditional Types追加以前のこのライブラリは内部でかなり複雑な事をしていてそんな簡単に読めるものじゃなかったのですが、今はかなり読みやすくなりました。
Conditional Typesの勉強にもおすすめです。
https://github.com/gcanti/typelevel-ts/blob/master/src/index.ts

7
4
1

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
4