Issue
I'm new to programming and JavaScript, i tried creating an interface for a code challenge, but i keep getting this error message:
Type '{ 1100: { albumTitle: string; artist: string; tracks: string[]; }; 2468: { albumTitle: string; artist: string; tracks: string[]; }; 1245: { artist: string; tracks: never[]; }; 5439: { albumTitle: string; }; }' is not assignable to type 'collectionInfo'.
Object literal may only specify known properties, and '1100' does not exist in type 'collectionInfo'.ts(2322)
Please i need your suggestions on how to resolve this or how to create a typescript interface that will eliminate this error message.
This my typescript interface attempt:
interface collectionInfo {
id : {
albumTitle: string | number |;
artist: string | number |;
tracks: string[] | number[] | null;
}
}
const recordCollection: collectionInfo = {
1100: {
albumTitle: "Prisoner",
artist: "Lucky Dube",
tracks: ["Prisoner", "Don\'t Cry"],
},
Solution
You have 2 options.
First is to use [id: number] like this:
interface collectionInfo {
[id: number] : {
albumTitle: string | number | null;
artist: string | number | null;
tracks: string[] | number[] | null;
}
}
const recordCollection: collectionInfo = {
1100: {
albumTitle: "Prisoner",
artist: "Lucky Dube",
tracks: ["Prisoner", "Don\'t Cry"],
}
}
And the second way is to add id to properties and then use an array instead like this:
interface collectionInfo {
id: number;
albumTitle: string | number | null;
artist: string | number | null;
tracks: string[] | number[] | null;
}
const recordCollection: collectionInfo[] = [
{
id: 1100,
albumTitle: "Prisoner",
artist: "Lucky Dube",
tracks: ["Prisoner", "Don\'t Cry"],
}
]
Answered By - Amirhossein
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.