DEV Community

MOHSIN ALI SOOMRO
MOHSIN ALI SOOMRO

Posted on

Prefer more precise alternative to the string Types in Typescript

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"
}
Enter fullscreen mode Exit fullscreen mode

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",
}
Enter fullscreen mode Exit fullscreen mode

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" 
Enter fullscreen mode Exit fullscreen mode
interface Album{
 artist:string;
 title:string;
 releaseDate:Date; 
 recordingType:RecordingType; 
}
Enter fullscreen mode Exit fullscreen mode
const kindOfBlue:Album ={
 artist:"Miles Devid",
 title:"Kind of blue",
 releaseDate:new Date("1959-08-18"),
 recordingType:"studio",
}
Enter fullscreen mode Exit fullscreen mode

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)