Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic import json file

I used to load a json file like this:

import faq from './faq.json'

interface FAQ {
   title: string
   body: string
}

interface SiteConfig {
    title: string
    faqs: FAQ[]
}

sites: {[key: string]: SiteConfig} = {
    siteA: {
        title: 'xx',
        faqs: faq
    }
}

Now I want to use dynamic imports:

interface FAQ {
   title: string
   body: string
}

interface SiteConfig {
    title: string
    faqs: () => FAQ[]
}

sites: {[key: string]: SiteConfig} = {
    siteA: {
        title: 'xx',
        faqs: (): Promise<FAQ[]> => import('./faq.json')
    }
}

fails with:

Type 'Promise<typeof "*.json">' is not assignable to type 'Promise<FAQ[]>'.
like image 504
Chris Avatar asked Nov 08 '22 11:11

Chris


1 Answers

Typescript give you an error because import return a promise of type JSON, not FAQ[] and therefore your error.

Try instead:

sites: {[key: string]: SiteConfig} = {
    siteA: {
        title: 'xx',
        faqs: (): Promise<any> => import('./faq.json')
    }
}

You could also make faqs an async function

sites: {[key: string]: SiteConfig} = {
    siteA: {
        title: 'xx',
        faqs: async (): Promise<any> => await import('./faq.json')
    }
}
like image 152
Attaque Avatar answered Nov 15 '22 11:11

Attaque