The domain of string type is big
Suppose you're building music collection and you want to define a type for an album
Attemp:
interface Album{
artist:string;
title:string;
releaseDate:string; //YYYY-MM-DD
recordingType:string; // "live" or "studio"
}
The prevelance of string types and the type information in comments are strong indications that this interface isn't quite right. Here is what can go wrong.
const kindOfBlue:Album ={
artist:"Miles Devid",
title:"Kind of blue",
releaseDate:"auguest 17th 1959",
recordingType:"Studio",
}
Problem 1:
Date is not formated
Problem 2:
recordingType Studio is small spell but it is capital.
How to narrow down string and solve these problem?
type RecordingType="studio" | "live"
interface Album{
artist:string;
title:string;
releaseDate:Date;
recordingType:RecordingType;
}
const kindOfBlue:Album ={
artist:"Miles Devid",
title:"Kind of blue",
releaseDate:new Date("1959-08-18"),
recordingType:"studio",
}
With these changes Typescript is able to do a more thorough check for errors
Make more precise type to error pron the code.
Thanks.
Top comments (0)