首页 > 解决方案 > 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

标签: typescripttype-parameter

解决方案


推荐阅读