我正在为第三方js库创建一个TypeScript定义文件.一项所述的方法允许对选择对象,并且选项对象的属性中的一个接收来自列表的字符串:"collapse","expand","end-expand",和"none".
我有一个options对象的接口:
interface IOptions {
indent_size?: number;
indent_char?: string;
brace_style?: // "collapse" | "expand" | "end-expand" | "none"
}
Run Code Online (Sandbox Code Playgroud)
接口是否可以强制执行此操作,因此如果您包含IOptions具有该brace_style属性的对象,它将只允许可接受列表中的字符串?
Rya*_*n Q 164
这在1.8版本中发布为"字符串文字类型"
页面示例:
interface AnimationOptions {
deltaX: number;
deltaY: number;
easing: "ease-in" | "ease-out" | "ease-in-out";
}
Run Code Online (Sandbox Code Playgroud)
小智 76
试试这个
export type ReadingTypes = 'some'|'variants'|'of'|'strings';
export interface IReadings {
param:ReadingTypes
}
Run Code Online (Sandbox Code Playgroud)
Wil*_*een 15
TS 提供对特定字符串值的类型化,称为String 文字类型。
以下是如何使用它们的示例:
type style = "collapse" | "expand" | "end-expand" | "none";
interface IOptions {
indent_size?: number;
indent_char?: string;
brace_style1?: "collapse" | "expand" | "end-expand" | "none";
brace_style2?: style;
}
// Ok
let obj1: IOptions = {brace_style1: 'collapse'};
// Compile time error:
// Type '"collapsessss"' is not assignable to type '"collapse" | "expand" | "end-expand" | "none" | undefined'.
let obj2: IOptions = {brace_style1: 'collapsessss'};
Run Code Online (Sandbox Code Playgroud)
Dud*_*ude 14
另一种可能性是做类似的事情:
export type BraceStyleOptions = "collapse" | "expand" | "end-expand" | "none";
export interface IOptions{
indent_size?: number;
indent_char?: string;
brace_style?: BraceStyleOptions;
}
Run Code Online (Sandbox Code Playgroud)
这样,您就可以在其他界面的任何地方重用您的选项。
也许不完全是你想要的,但对你来说,它Enum似乎是一个完美的解决方案.
enum BraceStyle {Collapse, Expand, EndExpand, None}
interface IOptions {
indent_size?: number;
indent_char?: string;
brace_style?: BraceStyle
}
Run Code Online (Sandbox Code Playgroud)
然而,枚举是基于数字的.这意味着在运行期间,例如BraceStyle.Collapse在这种情况下,实际值将为0.但是,您可以将它们与其他甚至非打字脚本一起使用,因为它们会编译为对象.这是BraceStyle编译和运行后的样子:
{
0: "Collapse",
1: "Expand",
2: "EndExpand",
3: "None",
Collapse: 0,
Expand: 1,
EndExpand: 2,
None: 3
}
Run Code Online (Sandbox Code Playgroud)
如果你想字符串时,可以使用静态成员类,描述在这里
我喜欢这种方法,因为它避免了在多个地方使用相同的硬编码字符串的需要。
可以创建一个枚举,其中值是字符串
export enum VISIBILITY {
PUBLISH = "publish",
DRAFT = "draft"
}
Run Code Online (Sandbox Code Playgroud)
然后可以将此枚举用作接口或类上的类型
export interface UserOptions {
visibility: VISIBILITY
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42276 次 |
| 最近记录: |