TypeScriptインターフェースで特定の文字列を要求する方法 質問する

TypeScriptインターフェースで特定の文字列を要求する方法 質問する

サードパーティの js ライブラリ用の TypeScript 定義ファイルを作成しています。 メソッドの 1 つではオプション オブジェクトが許可され、オプション オブジェクトのプロパティの 1 つでは、、、、および のリストから文字列を受け入れ"collapse"ます。"expand""end-expand""none"

オプション オブジェクト用のインターフェイスがあります:

interface IOptions {
  indent_size?: number;
  indent_char?: string;
  brace_style?: // "collapse" | "expand" | "end-expand" | "none"
}

インターフェイスでこれを強制して、プロパティIOptionsを持つオブジェクトを含める場合にbrace_style、許容リストにある文字列のみを許可するようにできますか?

ベストアンサー1

これはバージョン1.8で「文字列リテラル型」としてリリースされました。

Typescript の新機能 - 文字列リテラル型

ページからの例:

interface AnimationOptions {
  deltaX: number;
  deltaY: number;
  easing: "ease-in" | "ease-out" | "ease-in-out";
}

おすすめ記事