In my API, I need to define a type for representing an iso datetime string.
I want to ensure that not just any string can be assigned to it.
I want the compiler to catch any invalid assignments so I can handle them appropriately.
So in Golang, I would like something similar to this: type Time string
The following code is accepted in TS, but I want to prevent this assignment: const time: Time = "..."
type Time = string;
const message: string = 'hello world';
const time: Time = message;
Edit 1:
By using the Json article below, I was able to restrict arbitrary strings from being passed to the Time
type, although reverse assignment is still possible with no errors at
const someType: number = fourthOfJuly;
enum DateStrBrand { }
export type DateStr = string & DateStrBrand;
const fourthOfJuly = toDateStr('2017-07-04');
const someType: string = fourthOfJuly;
function checkValidDateStr(str: string): str is DateStr {
return str.match(/^\d{4}-\d{2}-\d{2}$/) !== null;
}
export function toDateStr(date: string): DateStr {
if (typeof date === 'string') {
if (checkValidDateStr(date)) {
return date;
} else {
throw new Error(`Invalid date string: ${date}`);
}
}
throw new Error(`Shouldn't get here (invalid toDateStr provided): ${date}`);
}