typescript - Parametrized type compiler bug or proper program?
问题描述
I'm surprised this program compiles. I would think the strLengthOne
declaration/initialization line would be flagged as a type error. Should not T
describe different types for the two different usages? One, the type that contains the single member "^...$"
and the other the type that contains the single member "^.$"
? Or do I misunderstand what types are being bound to T
during usage?
class RegularString<T extends string>
{
constructor(private readonly value: string, regexPatternConstraint: T)
{
if(!new RegExp(regexPatternConstraint).test(value))
throw new Error("Given value does not conform to regex " + regexPatternConstraint + ". found: " + value)
}
toString()
{
return this.value
}
}
const strLengthThree: RegularString<"^...$"> = new RegularString<"^...$">("ABC", "^...$")
const strLengthOne: RegularString<"^.$"> = strLengthThree // expected not to compile, but does
console.log(strLengthOne.toString().length) // prints 3
解决方案
推荐阅读
- php - < 和 > 在使用 DOM 文档创建 XML 中的节点值问题
- reactjs - 我可以同时将 Firestore 与 firebase sdk 和云功能一起使用吗?
- javascript - 如何使 boostrap 侧边栏默认关闭?
- python - 仅在所选 xlim 内显示 yticks
- sql - 物化视图并发刷新比非并发刷新花费的时间要长得多
- react-native - react-router-native,NativeRouter.js 模块解析失败 - 意外令牌
- javascript - 如何在年龄验证弹出窗口中使用带有是/否按钮的 JavaScript?
- azure - Azure 数据目录与 Azure SQL Server 元数据接口 - 发布数据源时不获取 Azure SQL Server 元数据
- java - 如何使用 Quarkus 以两种方式 SSL 从 REST 服务中的请求中检索客户端证书
- c++ - 在 c++/mysql 项目中使用单个preparedStatement 进行多次插入