我在试图为以下内容编写类型时遇到了困难:
type Language = 'en' | 'nl';
interface CacheObject {
[key: string | number | Language]: string;
}
const cache: CacheObject = {};
export const init = (dir: string): Promise<void> =>
fsPromises.readdir(dir).then(files =>
files
.filter(files => files.endsWith('.json'))
.forEach(async file => {
cache[file.slice(0, -5)] = await import(`${dir}/${file}`);
})
);
export const translate = (lang: Language): any => (key: string) =>
key.split('.').reduce((acc, val) => acc[val], cache[lang]);问题如下:
const cache: CacheObject
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'CacheObject'.
No index signature with a parameter of type 'string' was found on type 'CacheObject'.const cache: CacheObject
Element implicitly has an 'any' type because expression of type 'Language' can't be used to index type 'CacheObject'.
Property 'en' does not exist on type 'CacheObject'.有人能帮我指出正确的方向吗?
发布于 2019-07-11 09:04:07
您忽略了正在得到的另一个错误:An index signature parameter type must be 'string' or 'number' ( TS中可能有另一个错误,该错误可能会被其他错误所抑制),在测试代码时,错误会丢失,但在对代码进行一些非相应的更改后出现。玩弄错误)
如果要使用Languages向类型添加一些已知元素,则需要在交集中使用包含索引签名的类型的映射类型:
type CacheObject = {
[key: string]: string;
[key: number]: string;
} & Partial<Record<Language, string>>如果您只有索引签名来保持编译器对字符串索引的沉默,但是对象只能包含您可以考虑转换索引表达式的语言:
type CacheObject = Partial<Record<Language, string>>
cache[file.slice(0, -5) as Language] = await import(`${dir}/${file}`);https://stackoverflow.com/questions/56984137
复制相似问题