【发布时间】:2018-08-30 10:59:06
【问题描述】:
在我的 Angular 项目中,我想创建一个从字符串扩展的自定义类型。我的情况是我想创建一个“ID”类型来将字符串与 idstring 分开。
let str = String("tutu");
let id = ID("ec1s69azs");
this.service.getUserById(str) => doesn't compile;
this.service.getUserById(id) => compile;
将来,我可能想在“ID”类型中添加 id 验证器
我想知道这是否可能,因为我尝试了很多“黑客”,但没有一个能给我想要的结果。
class ObjectID extends String {
}
export type ID = ObjectID;
或
interface StringConstructor {
new(value?: any): String;
(value?: any): string;
readonly prototype: String;
fromCharCode(...codes: number[]): string;
}
export type ID = StringConstructor;
【问题讨论】:
-
为什么需要在ID类中验证ID?
-
验证 id 格式,例如,我将能够从我的服务器验证 id。
-
我在想你有一些 ID 格式的逻辑(例如,如果 ID 有一些字母,用户将能够做某事)。但是客户端是 UI,因此客户端必须信任来自您服务器的数据,而服务器不能信任来自客户端的数据。看来您的总体思路有误。
-
你是对的,但它更多的是用于调试目的和编程自动完成和实现,这只是一个例子。
标签: angularjs string typescript types primitive