Home > Enterprise >  Access json thougth interface in Typescript
Access json thougth interface in Typescript

Time:10-09

I have this interface

interface User{
    name: String,
}

Then this method:

printValue(path: WhatGoesHere?<User>){ // some type for helping autocomplete
    const JSON = {
        name: "Andres",
    }
    console.log(JSON[path]);
}

What i want is to have "intellisense" for sending the path param, so i want to do something like

printValue(User.name); // here intelisense shows and helps to write User.name

and get as result "Andres"

Is this possible? thanks in advance

CodePudding user response:

interface User {
  name: String;
}

function printValue(path: keyof User) {
  const JSON = {
    name: "Andres",
  };
  console.log(JSON[path]);
}

printValue('name')

In this way you can access

  • Related