0

I am trying to create a typescript interface, with a dynamic constraint on keys, that the following objects could extend:

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

1 Answer 1

1

if you want more type specific then you can do like below

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;
      }
    }

but i prefer more specific definition than dynamic key, like below

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;
    }

Example:

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

 let y:PData={
    id:"A",
   avatar: "imahe",
  thumbnails: {
    avatar:{
      "50x50": "",
      "100x100": "",
    }
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

updated the post. now it will serve your purpose

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.