打字稿中严格的打字别名

bsr

我想定义一个类型来表示我的API收到的iso datetime字符串。我要确保,尽管表示形式是字符串,但是不能将任何字符串分配给它。编译器应捕获这些分配,以便我可以进行转换(如果适用)。所以我想在golang中对此有所帮助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}`);
}

打字稿游乐场

bsr

基于上面的@jcalz的commnet,这就是我在以下资源的帮助下想到的。

https://basarat.gitbook.io/typescript/main-1/nominaltyping

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章