以前書いた記事の段階では、 typescript-generator
で requiredAnnotations
を指定すると、プリミティブ型のフィールド/GetterについてもOptional Properties(null設定可能)扱いとなっていた。
2021年3月の更新で、プリミティブ型をまとめて必須(非null)にできるオプションが追加されていたのでメモ。
環境
追加されたオプション
primitivePropertiesRequired
という boolean
型のパラメーターが追加されている。プロパティの説明はこちら。
optionalProperties
がデフォルトの useSpecifiedAnnotations
の場合、 requiredAnnotations
を指定していなければ各プロパティは必須になるため、 primitivePropertiesRequired
は requiredAnnotations
との併用前提と思われる。
Gradleであれば、以下のように generateTypeScript
タスクにパラメーターを追加するだけでいい。
generateTypeScript { // 中略, requiredAnnotations 指定済み primitivePropertiesRequired = true }
使用例
以前の記事から設定およびクラスを流用。
build.gradle
の変更箇所は以下。
buildscript { // 中略 dependencies { // バージョンを 2.30.840 に変更 classpath 'cz.habarta.typescript-generator:typescript-generator-gradle-plugin:2.30.840' } } generateTypeScript { // 中略 primitivePropertiesRequired = true }
出力対象のクラスは前回のリクエストクラスをそのまま流用。
package hepokon365.request; @lombok.Data public class ExampleRequest implements java.io.Serializable { @javax.validation.constraints.NotNull private String stringValue; private boolean booleanValue; private hepokon365.enums.ExampleEnum enumValue; }
出力結果は、以下のように、従来はオプションプロパティだった booleanValue
が、プリミティブ型のため必須プロパティとなる。
export namespace Endpoint { export interface ExampleRequest { stringValue: string; booleanValue: boolean; enumValue?: ExampleEnum | null; } }
振り返り
プリミティブ型に @javax.validation.constraints.NotNull
などのnullチェックアノテーションをつけると、IDEから警告が出たりするため、運用として boolean
なら Boolean
、 int
なら Integer
などのラッパークラスにしてアノテーションを付与することで対応していた。
とはいえ、プリミティブ型のままであれば自明なことを、プラグインの仕様に合わせるため曲げてコーディングしていたことは否めないため、この変更はかなりうれしい。