问题
在Typescript中,有没有一种方式可以定义一个类型,它只是字符串字面量,而不包括string
本身?
请注意,我并不是在谈论某个特定的字符串字面量列表;对于这种情况,简单的联合类型"Value1" | "Value2"
或枚举类型将起作用。我说的是任何字符串字面量,但不包括string
本身。
示例代码
type OnlyStringLiterals = ...; // <--- what should we put here?
const v1: OnlyStringLiterals = "hi"; // should work
const v2: OnlyStringLiterals = "bye"; // should work
// and so should be for any single string value assigned
// But:
const v3: OnlyStringLiterals = ("red" as string); // should NOT work -- it's string
应用场景
我正在对代码中的类型进行品牌化,并将品牌名称作为模板传递给我的父类。请参见下面的代码:
abstract class MyAbstractClass<
BRAND_T extends string,
VALUE_T = string
> {
constructor(private readonly _value: VALUE_T) { }
getValue(): VALUE_T { return this._value; }
private _Brand?: BRAND_T; // required to error on the last line, as intended!
}
class FirstName extends MyAbstractClass<"FirstName"> {
}
class AdminRole extends MyAbstractClass<"AdminRole"> {
}
class SubClassWithMissedName extends MyAbstractClass<string> {
// I want this to error! ........................ ^^^^^^
}
function printName(name: FirstName) {
console.log(name.getValue());
}
const userFirstName = new FirstName("Alex");
const userRole = new AdminRole("Moderator");
printName(userRole); // Already errors, as expected
我希望确保每个子类向父类传递的是一个字符串字面量,而不仅仅是字符串
。