Reputation: 6007
I have this TypeScript interface definition:
interface FieldInterface {
label: string;
placeholder: string;
title: string;
}
I have this data structure in first model:
fields = {
name: {
label: '...',
placeholder: '...',
title: '...'
},
age: {
label: '...',
placeholder: '...',
title: '...'
},
birth_place: {
label: '...',
placeholder: '...',
title: '...'
}
};
I have this data structure in second model:
fields = {
city: {
label: '...',
placeholder: '...',
title: '...'
},
zip: {
label: '...',
placeholder: '...',
title: '...'
},
street_address: {
label: '...',
placeholder: '...',
title: '...'
},
house_number: {
label: '...',
placeholder: '...',
title: '...'
}
};
Can I say something like this somehow, like this?:
interface FieldContainerInterface {
*: FieldInterface;
}
I want to say in interface all proerties must be an instace of FieldInterface
.
Can I do somehow?
Upvotes: 2
Views: 57
Reputation: 4415
In addition to the indexable types, Typescript defines a set of utility types. One of them is the Record<K, T>
which is what you need.
See https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt
type FieldContainerInterface = Record<string, FieldInterface>
Upvotes: 1
Reputation: 6078
You can use indexable-types (as mentioned in comment above)
interface FieldInterface {
label: string;
placeholder: string;
title: string;
}
interface FieldContainerInterface {
[key: string]: FieldInterface;
}
const fields: FieldContainerInterface = {
name: {
label: '...',
placeholder: '...',
title: '...'
},
age: {
label: '...',
placeholder: '...',
title: '...'
},
birth_place: {
label: '...',
placeholder: '...',
title: '...'
}
};
Upvotes: 3