Prefer precise string types
April 2, 2022
String type is big and giving variable a string type will give you a lot of possibilities input values. But with the great power comes great responsibility. Suppose you're building a book collection and want to define a type for a book. Here's an attempt to define a book type:
interface Book { title: string; writer: string; publishedDate: string; // YYYY-MM-DD bookType: string; // hardcover, paperback, ebook}
That interface seems right but actually not. Here's what can go wrong:
const book: Book = { title: 'Chemistry 12', writer: 'Marthen Kanginan', publishedDate: 'May 4th, 1945', // ooops, wrong format bookType: 'Hardcover' // ooops again, wrong type};
The publishedDate
and bookType
can be narrowed down to a more precise type. For publishedDate
field it's better to use a Date
object and avoid formatting issue. Then, for the bookType field, you can define a union type with just expected values. Here's the same interface with more precise types:
type BookType = 'hardcover' | 'paperback' | 'ebook';interface Book { title: string; writer: string; publishedDate: Date; bookType: BookType;}
With these changes Typescript is able to do a more thorough validation of the data.
const book: Book = { title: 'Chemistry 12', writer: 'Marthen Kanginan', publishedDate: new Date('1945-05-04'), bookType: 'Hardcover' // type Hardcover is not assignable to type BookType};
Another example misuse of string is in function parameters. Let's say you want to create simple find by bookType function. Instead using string type, you can use a union type with just expected values.
If create function with parameters that expected to be properties on an object we can use keyOf T
to narrow down the type of the parameter. For example pluck
function with generic.
function pluck<T, K extends keyof T>(records: T[], key: K): T[K][] { return record.map(r => r[key]);}
Wrap up
- Avoid "stringly typed" code. Prefer more precise types where not every value is possible.
- Use union types to define more precise types.
- Prefer
keyOf
T to string for function parameters that are expected to be properties of an object.