我希望定义一种类型来表示API接收到的ISO日期时间字符串。我想要保证虽然该表示是字符串,但不能分配给任何字符串。编译器应该捕获这些赋值,以便我可以在适用时进行转换。因此,我想在golang中实现类似于
以下TS代码是允许的,我需要防止这种分配:
type Time string
的东西。以下TS代码是允许的,我需要防止这种分配:
const time: Time = "..."
type Time = string;
const message: string = 'hello world';
const time: Time = message;
编辑1:
通过下面提到的Json文章,我可以增加安全性,防止任意字符串传递到Time
类型,但反过来是可能的。 在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}`);
}
const someType: string = fourthOfJuly;
没有错误。” 这是个问题吗?DateStr
应该是string
的子类型,因此可以将DateStr
值分配给string
变量,但反之则不行。这里还有什么需要回答的吗? - jcalzconst someType: number = fourthOfJuly;
- bsr