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)

Meh.
  • 234
  • 2
  • 12
  • 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. – Aplet123 Aug 15 '21 at 00:34
  • There's the option of using a [type assertion](https://stackoverflow.com/questions/15826745/typescript-creating-an-empty-typed-container-array), but for JSON there might be a better solution. – user202729 Aug 15 '21 at 02: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."? – Meh. Aug 15 '21 at 02:22

0 Answers0