5

I have this line of code that makes Typescript fire off an error:

const owner:boolean = jsonFile.owners.includes("10");

jsonFile is what I did from

import * as jsonFile from './dir/to/json/file.json'

Owners is an empty string[].

This is the error:

Argument of type 'string' is not assignable to parameter of type 'never'.

I know that I need to assign the type to this array, e.g. make it never[] -> string[], how would I do that? Preferably without strictNullChecks under tsconfig (solves this problem)

3
  • 2
    If you want to get the most out of a JSON object in typescript, I'd suggest making an interface for what you expect the JSON object to be (e.g. interface JSONFile { owners: string[] }) then casting the imported object to that type. Commented Aug 15, 2021 at 0:34
  • There's the option of using a type assertion, but for JSON there might be a better solution. Commented Aug 15, 2021 at 2:18
  • Hmm. I ended up having to force myself to use this snippet of code: const config:config = require('./config.json'); and I did use an interface (worked). This is what you mean by "casting the imported object to that type."? Commented Aug 15, 2021 at 2:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.