T
T
TRUEC0DER2022-03-05 13:26:43
Node.js
TRUEC0DER, 2022-03-05 13:26:43

How to specify data types in imported json file?

There is this code. When trying to add an object to a file, it gives an error. In which direction to dig?

error TS2345: Argument of type 'IUser' is not assignable to parameter of type 'never'.

import db from './data/db.json'

interface IUser {
    id: number
}

const create = (user: IUser) => {
    db.push(user)
}

create({
    id: 1,
})

console.log(db)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2022-03-05
@TRUEC0DER

https://www.typescriptlang.org/tsconfig#resolveJso...
Or create a db.json.d.ts file next to db.json with the following content:

declare const JSON: {
    id: number;
}[];
export default JSON;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question