Chris
Chris

Reputation: 14218

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[]>'.

Upvotes: 5

Views: 4615

Answers (1)

Nicolai Lissau
Nicolai Lissau

Reputation: 8312

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')
    }
}

Upvotes: 1

Related Questions