I have a question about mixed types in object values
I have an empty object with interface that I fill out later with the code. I add strings and numbers to it.
interface CardDataObject {
[key: string]: any
}
const data: CardDataObject = {}
data.number = number
data.string = string
That's how I add items later
With 'any' everything works fine, but my teacher says that I have to define it better and without 'any' type
Is there any way to create a universal interface for an object not knowing the type of values in advance?
CodePudding user response:
Your teacher is right, any
is to avoid at all cost because it basically disables TypeScript so it's like you write plain JavaScript.
You add strings and numbers to it? Then type it like this:
interface CardDataObject {
[key: string]: string | number
}
Shortest variant:
type CardDataObject = Record<string, string | number>
CodePudding user response:
I think it's not possible to not know the type at all in advance, typescript needs to know at least a range of types which are possible.
Look at these options:
- If you know that you going to use your interface only with numbers and strings (and maybe others) you can use then
union
types, it looks like -number | string
An example:
interface CardDataObject {
[key: string]: number | string
}
const data: CardDataObject = { key1: 'text', key2: 100 };
Union types - https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types
- The other option, if you want it to work with all possible types is to use 'generics'. You can declare an interface with a generic type and then choose later which type exactly it should be.
An example:
interface CardDataObject<T> {
[key: string]: T
}
const dataNumbers: CardDataObject<number> = { key1: 100 };
const dataStrings: CardDataObject<string> = { key1: 'text' };
Typescript generics - https://www.typescriptlang.org/docs/handbook/2/generics.html