typescript - 使用“对象名称中的键”时设置键类型
问题描述
我正在尝试像这样设置对象的键类型:
type TypeSample = {
[key: string]: string
}
同时还指定密钥来自这样的枚举:
enum EnumSample {
'ok' = '200',
}
type TypeSample = {
[key in EnumSample]: string
}
未设置密钥类型会导致错误Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'TypeSample'
出现在我的“getter”功能上。
我的问题:如何修改“TypeSample”以让 TypeScript 知道它只会有字符串键?
注意:对于代码的其他部分来说,“EnumSample”实际上是一个 ENUM 而不是 TYPE/INTERFACE,这一点很重要。
语境:
这是我正在使用的代码的精简版本:
enum SupportedHttpStatuses {
'ok' = '200',
'badRequest' = '400',
'imATeapotSafe' = '418a',
'imATeapot' = '418b',
}
type StatusMapType = {
[key in SupportedHttpStatuses]: StatusType // I want to set the key type here
}
type StatusType = {
code: number, // status code to send to the browser
title: string, // error title
description: string // error description
}
class Test {
public static STATUS_MAP: StatusMapType = {
'200': {
code: 200,
title: 'OK',
description: 'This request has succeeded.',
},
'400': {
code: 400,
title: 'Bad Request',
description: 'This request is missing data or contains invalid information.',
},
'418a': {
code: 200,
title: 'I\'m A Teapot!',
description: 'This request was successful but it is april fools day.',
},
'418b': {
code: 418,
title: 'I\'m A Teapot!',
description: 'This request was successful but it is april fools day.',
},
}
public static async getStatusMap(statusId: string): Promise<StatusType> {
return this.STATUS_MAP[statusId] // Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'StatusMapType'
}
}
解决方案
我建议你更改签名
getStatusMap(statusId: string): Promise<StatusType>
至
getStatusMap(statusId: SupportedHttpStatuses): Promise<StatusType>
然后 this.STATUS_MAP[statusId] 将知道 statusId 是 SupportedHttpStatuses ,因此当 STATUS_MAP 被索引时将返回 StatusType
推荐阅读
- python - 壁虎驱动问题
- java - 更新集
如果 Person 存在,或者如果不存在则添加它们 - javascript - Reduxjs 或简单地声明
- c++ - 在 noexcept 规范中是否允许使用 `this`?
- spring - Spring post方法“缺少所需的请求正文”
- java - 在 Windows 7 中绕过 System32 / SysWOW64 javaw.exe 从 VBA 宏运行 java
- angular - Angular 6 - 从 MongoDB、Typescript 中删除数据
- json - Golang 和 gRPC Marshal/Unmarshal 或手动方法
- c# - 如何从 asp.net web 表单中的 gridview 获取值?
- java - Vaadin 绑定 API 和 Id