“const”断言只能应用于对枚举成员、字符串、数字、布尔值、数组或对象的引用

Bru*_*tos 6 javascript typeof typescript

Object.keys() as const不工作。我怎样才能做到这一点?(假设我不知道对象的内容,也不知道我的对象有哪些键)

const values = Object.keys(myObject) as const;
Run Code Online (Sandbox Code Playgroud)

我需要as const获取字符串文字类型

let name: typeof values[number];
Run Code Online (Sandbox Code Playgroud)

Rub*_*unk 15

You can do

let name: keyof typeof myObject
Run Code Online (Sandbox Code Playgroud)

See this question for why strongly typing Object.keys might be a bad idea.