Reputation: 318
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"
}
}
Upvotes: 0
Views: 1153
Reputation: 2823
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": "",
}
}
}
Upvotes: 1