如何在 TypeScript 接口中要求特定字符串 [英] How to require a specific string in TypeScript interface
问题描述
我正在为第 3 方 js 库创建一个 TypeScript 定义文件.其中一种方法允许选项对象,选项对象的属性之一接受列表中的字符串:"collapse"
, "expand"
, "end-expand"
和 "none"
.
I'm creating a TypeScript definition file for a 3rd party js library. One of the methods allows for an options object, and one of the properties of the options object accepts a string from the list: "collapse"
, "expand"
, "end-expand"
, and "none"
.
我有一个选项对象的接口:
I have an interface for the options object:
interface IOptions {
indent_size?: number;
indent_char?: string;
brace_style?: // "collapse" | "expand" | "end-expand" | "none"
}
接口是否可以强制执行此操作,因此如果您包含一个带有 brace_style
属性的 IOptions
对象,它将只允许可接受列表中的字符串?>
Can the interface enforce this, so if you include an IOptions
object with the brace_style
property, it will only allow a string that is in the acceptable list?
推荐答案
这是在 1.8 版中作为字符串文字类型"发布的
This was released in version 1.8 as "string literal types"
页面示例:
interface AnimationOptions {
deltaX: number;
deltaY: number;
easing: "ease-in" | "ease-out" | "ease-in-out";
}
这篇关于如何在 TypeScript 接口中要求特定字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!