打字稿:带有动态键的接口

时间:2021-05-05 11:27:10

标签: typescript

我正在尝试创建一个打字稿接口,对键具有动态约束,以下对象可以扩展:

{
  id: 35,
  avatar: "bar1",
  thumbnails: {
    avatar: { 
    "50x50": "bar2", 
    "100x100": "bar3"
  }
}
{
  id: 335,
  image: "foo1",
  thumbnails: {
    image: { 
    "50x50": "foo2", 
    "100x100": "foo3"
  }
}

1 个答案:

答案 0 :(得分:0)

如果你想要更具体的类型,那么你可以像下面这样

const AVATAR="avatar"
const IMAGE ="image"

type ThumbType= typeof AVATAR | typeof IMAGE

interface A{
      id: string;
      [key:ThumbType]: string;
      thumbnails: {
       [key: ThumbType]: { 
        "50x50": string; 
        "100x100": string;
      }
    }

但我更喜欢比动态键更具体的定义,如下所示

interface Resulation{
      "50x50": string;
      "100x100": string;
    }
    
    interface Image{
           image: string;
          thumbnails:{
           image: Resulation
          }
    }
    
    interface Avatar{
          avatar: string;
          thumbnails:{
           avatar: Resulation
          }
    }

    type PData= (Image| Avatar) &{
      id: string;
    }

示例:

let x:PData={
    id:"A",
   image: "imahe",
  thumbnails: {
    image:{
      "50x50": "",
      "100x100": "",
    }
  }
}

 let y:PData={
    id:"A",
   avatar: "imahe",
  thumbnails: {
    avatar:{
      "50x50": "",
      "100x100": "",
    }
  }
}