Reputation: 5367
I'm using the context module API to include some files in my project.
On a value that I extract from the values property typescript is giving me the error: TS2339: Property 'default' does not exist on type 'unknown'
.
How can I make this (strongly) typed?
const blogPosts = ((context): Data[] => {
const keys = context.keys();
const values = keys.map(context);
console.log('values: ', values);
// logs: (3) [Module, Module, Module]
// 0: Module { default: "---↵title: "A blog title"↵author: John↵date:… etc", __esModule: true, Symbol(Symbol.toStringTag): "Module"}
// 1: Module { default: "---↵title: "Another blog title"↵author: John↵date:… etc", __esModule: true, Symbol(Symbol.toStringTag): "Module"}
// 2: Module { default: "---↵title: "Yet another blog title"↵author: John↵date:… etc", __esModule: true, Symbol(Symbol.toStringTag): "Module"}
const data: Data[] = keys.map((key, index) => {
const value = values[index];
// TS2339: Property 'default' does not exist on type 'unknown'
return matter(value.default) as DocumentFrontMatter;
});
return data;
})(require.context('../posts', true, /\.md$/));
Edit: Removed the next part. Don't think it's in webpack-env. In @types/webpack and @types/webpack-env no notion of a 'default' is mentioned.
Note: I have added @types/webpack-env
to my projects dependencies, and used it in the tsconfig.json (source):
"types": [
"node",
"webpack-env"
]
Upvotes: 0
Views: 2747
Reputation: 5367
As I was working on the code I circumvented this issue. I happened to have to use the same function again and did a re-write which removed the need for the default key.
Note the __WebpackModuleApi.RequireContext
.
function importAll(webpackContext: __WebpackModuleApi.RequireContext): Data[] {
return webpackContext.keys().map((fileUrl) => {
const body = webpackContext(fileUrl);
const slug: string = fileUrl;
const document: DocumentFrontMatter = matter(body.default) as DocumentFrontMatter;
return {
slug,
document,
};
});
}
// ...
const posts = importAll(require.context('../posts', true, /\.md$/));
const events = importAll(require.context('../events', true, /\.md$/));
Upvotes: 2