Typescript: Missing data type in requiring json file.

Created on 24 Aug 2017  ·  7Comments  ·  Source: microsoft/TypeScript

TypeScript Version: 2.4.0 / nightly (2.5.0-dev.201xxxxx)

Code

// data.json
{
    "age": 123,
    "username": "Tom",
}
declare const require: any;

// 'age' and 'username' are inffered as any
const { age, username } = require('./data.json')

// wrong syntax
const { age as number, username as string } = require('./data.json')

// can't use destruction, and we cant get warnings when we assert incorrect types
const age: number = require('./data.json').age
const username: string = require('./data.json').username

Expected behavior:

Get the correct types of 'age' and 'username'

Actual behavior:

Thus require syntax can't get the actual types when handling json file.

Duplicate

Most helpful comment

you must define require data types! like this.

// data.json data like

// {
//     "name": "your name",
//     "age": 23
// }

interface Info {
    name: string;
    age: number;
}

const data: Info = require("./data.json");

All 7 comments

You should really be asking these basic general questions in other forums, like StackOverflow or Gitter.

const { age, username } = require('./data.json') as { age: number, username: string };
// or
const { age, username }: { age: number, username: string } = require('./data.json');

you must define require data types! like this.

// data.json data like

// {
//     "name": "your name",
//     "age": 23
// }

interface Info {
    name: string;
    age: number;
}

const data: Info = require("./data.json");

@kitsonk Thx for your reply and sorry for asking syntax. I came up this issue bcoz that I thought that it's may be a defect on requiring non-ts/js file at first.
I think that it is not much difficult to infer the data types which come from JSON file. Why not do the enhancement?

Then this is a duplicate of #9225.

Static analysis of JSON at design time has limited value and almost always needs some sort of assertion of what the real type/structure is for it to be handled as. Also the mechanics of importing JSON at runtime very widely at runtime and in a lot of cases, it is a structure returned from a remote request, where again, typing would need to be asserted because it cannot be statically identified.

@kitsonk Okay, maybe you are right, I'm just a little upset for the dev experience. The local JSON files have been imported into the compiling system, it should be well analyzed, manually assertion
on 'any' type may cause runtime errors.

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

Was this page helpful?
0 / 5 - 0 ratings