Home > OS >  How to use index signature for nested object in typescript?
How to use index signature for nested object in typescript?

Time:12-19

How to specify index signature for nested object? I have component where i need to define type for it.

const data = {
  name:'Jack',
  age:10,
  address: {
    city:'Boston',
    country:'USA'
  }
}

const DataCell = (data:{[key: string]: string })=> {
  return <span>{data.address.country}</span>
}

if i specify it like this I get Property 'country' does not exist on type 'String'. I do not want to hard code the interface.

CodePudding user response:

To specify an index signature for a nested object, you can use the following syntax:

const DataCell = (data: { [key: string]: { [key: string]: string } }) => {
  return <span>{data.address.country}</span>
}

This specifies that the data object has a string index signature, and the value of each property in the object has another string index signature. This allows you to access properties of the nested object using the dot notation, like data.address.country.

Alternatively, you can use a type alias to define the shape of the nested object:

type Address = {
  [key: string]: string
}

const DataCell = (data: { [key: string]: Address }) => {
  return <span>{data.address.country}</span>
}

This allows you to reuse the Address type elsewhere in your code, and makes the type definition easier to read and understand.

CodePudding user response:

I don't understand what you are trying to do but your declaration will result in the value data.address is string

you can style it like this instead:

interface Data {
  name: string
  age: number
  address: {
    city: string
    country: string
  }
}

const DataCell = (data: Data)=> {
  return <span>{data.address.country}</span>
}

CodePudding user response:

Since you know what your object looks like, you can simply use it as the type.

type User = {
  name: string;
  age: number
  address: {
    city: string
    country: string
  }
}

const DataCell = (data: User)=> {
  return <span>{data.address.country}</span>
}
  • Related