Home > Software engineering >  How to convert a JS k-v object to a typescript version?
How to convert a JS k-v object to a typescript version?

Time:05-01

I want to convert a js object into typescript version (we are refactoring the code) :( But I don't get how to migrate a JS JSON object into a correct TS format. For example, we have a JS object like this:

JS Object:
{
  "filter": {
    "price": {
      "$gte": 10,
      "$lte": 100
    },
    "symbol": "appl"
  },
  "sort": {
    "createdAt": -1
  }
}

So it's easy in js code that we declare a params = {} and we can insert params.filter[price] = .....

However, if we want to do it in Typescript, the compiler will complain that we need to determine the type, and it's hard because as you can see the "value" can be string or int or another object.

Do you have any ideas on it? Super thanks!!!!!

CodePudding user response:

There is no need to create a type/interface in order to parse JSON:

const json = `{
  "filter": {
    "price": {
      "$gte": 10,
      "$lte": 100
    },
    "symbol": "appl"
  },
  "sort": {
    "createdAt": -1
  }
}`

const data = JSON.parse(json)

console.log(data)

If you want too, you can create an interface and assign the parsed data to it. Note however that this doesn't validate that the parsed data matches the type/interface (it could be any arbitrary JSON data and it would be assigned to the result variable, but typescript would then only let you access the members that exist in the interface.

interface Data {
  filter: {
    price: {
      $gte: number
      $lte: number
    }
    symbol: string
  }
  sort: {
    createdAt: number
  }
}

const json = `{
  "filter": {
    "price": {
      "$gte": 10,
      "$lte": 100
    },
    "symbol": "appl"
  },
  "sort": {
    "createdAt": -1
  }
}`

const data: Data = JSON.parse(json)

console.log(data)
console.log(data.filter.symbol)

CodePudding user response:

If you're trying to validate JSON input, you're approaching it wrong. To validate JSON input using NodeJS you can use a package or library to compare it against a schema.

ajv is one module that does this job really well - have a look at that

CodePudding user response:

If you want type of specific object try using VSCode Paste JSON as Code extension or this website that will generate typescript interface from your object http://json2ts.com/ .

CodePudding user response:

You can use TypeScript interfaces to do so. You can easily generate TS using websites or extensions like https://app.quicktype.io/

TS

export interface Pokedex {
    filter: Filter;
    sort:   Sort;
}

export interface Filter {
    price:  { [key: string]: number };
    symbol: string;
}

export interface Sort {
    createdAt: number;
}

JS

{
  "filter": {
    "price": {
      "$gte": 10,
      "$lte": 100
    },
    "symbol": "appl"
  },
  "sort": {
    "createdAt": -1
  }
}

  • Related