首页 > 解决方案 > 使用“对象名称中的键”时设置键类型

问题描述

我正在尝试像这样设置对象的键类型:

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'
    }
}

标签: typescript

解决方案


我建议你更改签名

getStatusMap(statusId: string): Promise<StatusType>

getStatusMap(statusId: SupportedHttpStatuses): Promise<StatusType>

然后 this.STATUS_MAP[statusId] 将知道 statusId 是 SupportedHttpStatuses ,因此当 STATUS_MAP 被索引时将返回 StatusType


推荐阅读