【问题标题】:TS keyof typeof <Object> does not allow object.keys(<Object>) to be assigned?TS keyof typeof <Object> 不允许分配 object.keys(<Object>)?
【发布时间】:2022-01-09 06:32:59
【问题描述】:

我不明白这段代码有什么问题。

这是我的代码:

export type SportsTypes = keyof typeof SportsIcons

export const sports: SportsTypes[] = Object.keys(SportsIcons);

我正在将我的变量键入到对象的键中。 但是,当我尝试将所述键的数组分配给这个变量时,我得到了 ts 错误: Type 'string[]' is not assignable to type '("Football" | "GameController" | "Tennis" | "Basketball" | "PingPong" | "Volleyball" | "HockeyPuck" | "Chess" | "AmericanFootball" | "Baseball" | "SandVolleyball")[]

【问题讨论】:

    标签: javascript reactjs typescript typeof keyof


    【解决方案1】:
    export type SportsTypes = keyof typeof SportsIcons
    
    export const sports = Object.keys(SportsIcons) as SportsTypes[];
    

    【讨论】:

    • 太棒了,这成功了。我什至知道这个规则并在这个应用程序的其他地方使用它,不知道为什么它在这里逃脱了我。谢谢!
    猜你喜欢
    • 2016-08-17
    • 2012-02-08
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    • 2023-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多