【发布时间】:2021-03-26 21:30:49
【问题描述】:
我有一个函数可以根据你给它的字符串提取一个值。当我执行函数时,如何使函数的输出键入它已提取的值。
const config = {
one: 'one-string',
two: 'two-string',
three: true,
four: {
five: 'five-string',
six: false
},
seven: [
'eight', 'nine', 'ten'
]
}
type Config = {
one: string;
two: string;
three: boolean;
four: {
five: string;
six: boolean;
}
seven: string[]
}
type GetConfig = (key: keyof Config) => Config[keyof Config];
export const getConfig: GetConfig = key => {
return config[key];
};
getConfig('seven').map(...);
目前我收到以下错误:
类型'string | 上不存在属性'map'布尔值 |字符串[] | { 五:字符串;六:布尔值; }'。属性“地图”不存在 输入“字符串”。
因为getConfig 没有像上面指出的那样被键入为数组,而只是被键入为任何一种可能的类型。
【问题讨论】:
标签: typescript