DEV Community

MOHSIN ALI SOOMRO
MOHSIN ALI SOOMRO

Posted on

3 2

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.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay