gpt4 book ai didi

typescript - 如何将一组字符串声明为一种类型?

转载 作者:搜寻专家 更新时间:2023-10-30 21:03:40 25 4
gpt4 key购买 nike

我想强制将一组字符串作为严格类型。用户应该只能传递与组中的字符串匹配的任何内容。我将如何实现它?

这是我目前所拥有的:

const types: Array<string> = [ 'text', 'password' ];

interface IAbstractFormElement {

value: string;
type: Array<types>;
required?: boolean;
disabled?: boolean;

}

当前错误:找不到名称“types”,这对我来说几乎像是一个范围问题。

最佳答案

如果您事先知道 type 属性的可能值是什么,那么您可以使用 string literals :

type types = "text" | "password";

const types: types[] = ["text", "password"];

interface IAbstractFormElement {
value: string;
type: types;
required?: boolean;
disabled?: boolean;
}

( code in playground )

关于typescript - 如何将一组字符串声明为一种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43380779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com