typescriptjson动态接口

typescriptjson动态接口,typescript,Typescript,我对typescript非常陌生,我想将下面的json转换成一个接口/类型,但是user1键是动态的,可能会有所不同,但是of键中的json将是相同的 { “代码”:200, “状态”:“成功”, “数据”:{ “用户1”:{ “名字”:“约翰”, “姓氏”:“史密斯”, “年龄”:25岁 } } } 到目前为止,我有以下资料。是否可以在根接口中将数据转换为映射,因为我在golang中就是这样做的 export interface Root { code: number status:

我对typescript非常陌生,我想将下面的json转换成一个接口/类型,但是user1键是动态的,可能会有所不同,但是of键中的json将是相同的

{
“代码”:200,
“状态”:“成功”,
“数据”:{
“用户1”:{
“名字”:“约翰”,
“姓氏”:“史密斯”,
“年龄”:25岁
}
}
}
到目前为止,我有以下资料。是否可以在根接口中将数据转换为映射,因为我在golang中就是这样做的

export interface Root {
  code: number
  status: string
  data: Data
}

export interface Data {
  user1: User1
}

export interface User1 {
  firstName: string
  lastName: string
  age: number
}

干杯


Brett

您可以使用索引签名:

export interface Root {
    code: number
    status: string
    data: Data
}

export interface Data {
    [key: string]: User
}

export interface User {
    firstName: string
    lastName: string
    age: number
}

这是我目前使用它的方式,但它不起作用

export interface Root {
    code: number
    status: string
    data: Data
}

export interface Data {
    [key: string]: User
}

export interface User {
    firstName: string
    lastName: string
    age: number
}

export const sendRequest = (url: string): Root => {
  const [data,setData]=useState([]);
  const getData=()=>{
    fetch(url
    ,{
      headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
       }
    }
    )
      .then(function(response){
        return response.json();
      })
      .then(function(myJson) {
        setData(myJson)
      });
  }
  useEffect(()=>{
    getData()
  },[])
  return JSON.parse(JSON.stringify(data));
}

const user = sendRequest(host + path) 

console.log(user.data?.[0]) 


我认为通用根目录更有用。嗯,它正在工作,但不确定我做了什么,它不再工作了。获取以下错误消息Uncaught(承诺中)TypeError:无法读取未定义数据的属性“firstname”?[0]。聚合如何使用它?``const user=sendRequest(host+path)console.log(user.data?[0])````export-const-sendRequest=(url:string):Root=>{const[data,setData]=useState([]);const-getData=()=>{fetch(url,{headers:{Content-Type':'application/json',Accept':'application/json'})。然后(函数(response){return response.json();})。然后(函数(myJson){setData(myJson)};}useffect(()=>{getData()},[])返回JSON.parse(JSON.stringify(data));}``这不是错误所在