-
Notifications
You must be signed in to change notification settings - Fork 12.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Missing data type in requiring json file. #18001
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. |
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 |
should be tracked by #7071 |
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed. |
TypeScript Version: 2.4.0 / nightly (2.5.0-dev.201xxxxx)
Code
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.
The text was updated successfully, but these errors were encountered: