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

TypeScriptでNominal Typingするときの推論結果

Posted at

TypeScriptで公称型っぽく書くときは推論の結果がneverにならないように注意したい、という話。

enum FooBrand { }
type FooId = string & FooBrand;
type BarId = string & { _barBrand: never };
type BuzId = string & { _buzIdBrand: never };
type BarBuzId = BarId & BuzId;

function foo() {//: never
    return "" as FooId;
}
function bar1() {//: BarId
    return "" as BarId;
}
function bar2() {//: string & { _barBrand: never }
    return "" as string & { _barBrand: never };
}
function barbuz1() {//: string & {_barBrand: never;} & {_buzIdBrand: never;}
    return "" as BarId & BuzId;
}
function barbuz2() {//: BarBuzId
    return "" as BarBuzId;
}
  • enumを使うとneverとして推論される
  • 使用箇所で直接&を使っていると中身が展開される

Brand自体を組み合わせなければそこまで厳しくわないが、
組み合わせて使いだすと結果が長いので一旦定義し直すほうがスッキリして見える。

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?