[英]Can I use array variable to define typescript?
Let say I have a constant variable假设我有一个常量变量
const STATUS = {
ACTIVE: "ACTIVE",
DELETED: "DELETED",
}
And I have a function which input is status我有一个 function 输入是状态
const handleStatus = (status) {
//do some thing
}
I want to define interface for status
just accept 'ACTIVE' and 'DELETED' so I have to manually define like bellow我想为
status
定义接口,只接受'ACTIVE'和'DELETED',所以我必须像下面这样手动定义
type status = 'ACTIVE' | 'DELETED'
const handleStatus = (status : status) {
//do some thing
}
Can I do something like我可以做类似的事情吗
type status = Object.values(STATUS)
Thanks!谢谢!
Edit: I define type status = (typeof STATUS)[keyof typeof STATUS]
But when I try to check if status is valid编辑:我定义
type status = (typeof STATUS)[keyof typeof STATUS]
但是当我尝试检查状态是否有效时
const validStatus = Object.values(STATUS)
if(!validStatus.includes(status)) {
//do something
}
Typescript throw error Typescript 抛出错误
Argument of type 'string' is not assignable to parameter of type ...
There're 2 options for you.有 2 个选项供您选择。 As a suggestion in comment to switch using
enum
in this case, another way is to use keyof
keyword in terms of still wanting to have a string literal as type:作为在这种情况下使用
enum
进行切换的评论中的建议,另一种方法是使用keyof
关键字,因为仍然希望将字符串文字作为类型:
type Status = keyof typeof STATUS;
PS: If you prefer the values as type rather than the keys, you need to tweak a bit more: PS:如果您更喜欢将值作为类型而不是键,则需要进行更多调整:
const STATUS = {...} as const // mark it as constant
type Status = (typeof STATUS)[keyof typeof STATUS];
Answer for newly added request对新增请求的答复
Looks like misunderstand between typing vs its value.看起来像是打字与其价值之间的误解。 You can't set a type as value which means you have to create a variable with the type you already defined (Don't define a type name as lowercase
status
) so here's the example:您不能将类型设置为值,这意味着您必须使用已定义的类型创建一个变量(不要将类型名称定义为小写
status
),因此示例如下:
type Status = (typeof STATUS)[keyof typeof STATUS];
// this is the value which needs to create with your created type
const status: Status = 'ACTIVE';
// you can set this type as: `Status[]` or
// you don't need to do so cause
// tsc can infer correct type as `Status[]`
const validStatus = Object.values(STATUS);
if(!validStatus.includes(status)) {
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.