我想要完成的简化版本。
const colors = {
red: "#8b0000",
green: "#008b00",
}
const logColor = (color: string) => {
console.log(colors[color])
}
这个错误来自console.log()
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ red: string; green: string; }'.
No index signature with a parameter of type 'string' was found on type '{ red: string; green: string; }'.
我需要做些什么来解决这个问题?
您需要使用keyof typeof colors
而不是string
。
const colors = {
red: "#8b0000",
green: "#008b00",
}
const logColor = <T extends keyof typeof colors>(color: T) => {
console.log(colors[color])
}