LoginSignup
7
3

More than 3 years have passed since last update.

[Typescript] enumよりもstring literalがイケてる

Posted at

TypescriptではCやJavaなどでもお馴染みのenumがサポートされているけど、string literalを使うことでコードの記述量の削減、コンパイル後のオブジェクト数の削減ができますよという話。
以下、具体例。

// A.ts
export enum Enum {
    Hoge = 'hoge',
    Fuga = 'fuga'
}
function enumFunc(val: Enum) {}
function typeFunc(val: 'hoge' | 'fuga') {}  // inlineで書くこともできる

// B.ts
// import {
//     Enum,  // import必須
//     enumFunc,
//     typeFunc
// } from './A.ts'
enumFunc(Enum.Hoge) // importしたenumを使わないといけない
typeFunc('hoge')  // typeのimportがいらない

これがjavascriptにコンパイルされると

// A.ts
export var Enum;
(function (Enum) {
    Enum["Hoge"] = "hoge";
    Enum["Fuga"] = "fuga";
})(Enum || (Enum = {}));
function enumFunc(val) { }
function typeFunc(val) { } // inlineで書くこともできる
// B.ts
// import {
//     Enum,  // import必須
//     enumFunc,
//     typeFunc
// } from './A.ts'
enumFunc(Enum.Hoge); // importしたenumを使わないといけない
typeFunc('hoge'); // typeのimportがいらない

になる。Enumオブジェクトが増えてしまっている。

以下、Playground
https://www.typescriptlang.org/play/#code/PTAEEEDoBcGcCgCmAPADgewE7VIgdgK4C2oAooSQN7yi2gAS6A5oqALygDkAFs4pwBoadAGIEmAQ3ZcAZuImd4AX3hy8AY2gBLdHlwUxGgBQA3CQBsAXGQoBKUJRVrNOvdACeqRIfWmL1nj5OUAAfWXlOe0daEFAtPHN4xEBzBkAPs0B5BkBlBkALBkAghmTAWQZAaIZ4eFiAIRgEWK0iDGwHMrA6G2IBGLBa+uhAUf1ACAymlv1iHyFYlo8vH0GlUBlMdBJOSGAoOEV8EYJjcmJIRhZ7GrqsaEB1BkB9Bk2iQCSGQH95QHiGQCsGQBEGbJfARQZX+Envbd9AixIh1QL9AHYMXVOgBkGF6ASIZvkA

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