[SOLVED] Get value of an Object type by key in TypeScript


I have an object type variable

let ref_schema_data: object

The value of ref_schema_data

{ '$schema': 'http://json-schema.org/draft-07/schema',
  '$id': 'tc_io_schema_top.json',
   [ { type: 'object', required: [Array], properties: [Object] } ] }

This is how I am assigning value to ref_schema_data

function load_schema(filename: string, filepath: string):object {
    let json_data = fs.readFileSync(path.join(filepath, filename),'utf8')
    return JSON.parse(json_data)

I am finding it difficult to get any value out of the object by key. For e.g. I need to get ref_schema_data["$id"] . But that’s not working .

What is the mistake I am doing .


The object type is very rarely useful. It doesn’t define any properties of the object, so no property access is allowed. Instead, define a type that matches your object’s shape. For instance:

interface Thingy {
    type: string;
    required: something[];   // I don't know from the question what you have in this array
    properties: something[]; // Or this one
interface SchemaData {
    $schema: "http://json-schema.org/draft-07/schema", // A string literal type
    $id: string;
    allOf: Thingy[]; // An array type

Then if you assign SchemaData as the type of ref_schema_data, you’ll be able access the properties in the object. (Obviously, you’ll have to fill in the something placeholders above.)

More in the handbook.

In a comment you’ve said:

the only thing is my schema properties are not constant , it will vary. So i thought difficult to have interface for same. My requirement is basically read JSON object and get value for some keys if exists

In that case, your interface uses an index signature (allow any property name), perhaps allowing the values to be anything (any):

interface SchemaData {
    [key: string]: any;

That says "a SchemaData is an object with any string as a property name, where all the properties have any type." It doesn’t provide virtually any type-safety, because when dealing with data that you don’t know the shape of, you can’t. 🙂

Live example on the TypeScript playground

Or you might just use any on ref_schema_data instead.

Live example on the TypeScript playground

Answered By – T.J. Crowder

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *