Javascript typescript中的严格typealias

Javascript typescript中的严格typealias,javascript,typescript,Javascript,Typescript,我想定义一个类型来表示API接收到的iso日期时间字符串。 我希望安全性,尽管表示是字符串,但不能为其分配任何字符串。 编译器应该捕获这些赋值,以便在适用的情况下进行转换。 所以我想在golang中输入时间字符串 TS中的以下代码是允许的,我需要阻止赋值const-time:time=“…” 编辑1: 通过下面提到的Json文章,我可以添加任意字符串不能传递到Timetype的安全性,但反过来也是可能的。const someType:number=fourthOfJuly时无错误 enum D

我想定义一个类型来表示API接收到的iso日期时间字符串。 我希望安全性,尽管表示是字符串,但不能为其分配任何字符串。 编译器应该捕获这些赋值,以便在适用的情况下进行转换。 所以我想在golang
中输入时间字符串

TS中的以下代码是允许的,我需要阻止赋值
const-time:time=“…”

编辑1:
通过下面提到的Json文章,我可以添加任意字符串不能传递到
Time
type的安全性,但反过来也是可能的。
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}`);
}

您最好的选择可能是使用一个带商标的字符串和一个typeguard


不过,我很高兴在键入完整的解释之前在谷歌上搜索了一下,因为。

基于上面@jcalz的commnet,这是我在下面资源的帮助下得出的结论


谢谢你,杰森。这是个巧妙的把戏。让我们看看是否有人有更好的办法在编译时检测所有错误。请注意,空的
enum
品牌自TS3.6以来就没有工作过;相反,我可能会使用一个带有私有成员的类,比如
class DateStrBrand{private DateStrBrand=“DateStr”}
“const someType:string=fourthOfJuly;
”这是问题吗?
DateStr
应该是
string
的子类型,因此您可以将
DateStr
值指定给
string
变量,但反之亦然。这里还有什么需要回答的?没有更好的编译时支持来支持您所做的工作,因为它们不是语言的一部分。@jcalz感谢您的确认。我做了一次编辑,显示分配数字或任何类型都没有错误。更糟糕的是:-)
constsometype:number=fourthOfJuly啊,空的
enum
品牌从TS3.6开始就不起作用了。相反,可以使用具有私有成员的类,如
类DateStrBrand{private DateStrBrand=“DateStr”}
或其他类似的类
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}`);
}
export interface DateStr extends String {
  ____dateStrBrand: string; // To prevent type errors
}

// Safety!
var fooId: Time = "..."; // error
fooId = "..." as any; // OK

// If you need the base string
var str: string;
str = fooId; // error
str = fooId as any; // OK