Typescript-有没有一种方法可以通过常量将类型应用于变量



这就是我所期望的(这不是有效的TS(:

const type1 = "number";
let myVariable1 : typeof<type1> = 12;
let type2 = "string" as const;
let myVariable2 : typeof<type2> = "foo";

有没有办法在TypeScript中应用这样的类型?

您可以使用条件类型:

type typeByString<T> = T extends "number" ? number : T extends "string" ? string : any;
type str = typeByString<"string">; // str is string
type num = typeByString<"number">; // num is number

这是受Sebastian Speitel的答案启发:

我们还可以使用个人类型的类型检查:

type Person = { name : string, age : number };
type typeByString<T> = T extends "Person" ? Person : number;
const a: typeByString<"Person"> = {name : "Foo", age : 20};
const b: typeByString<"other"> = 23;

也可以从字符串数组中选择字符串类型:

type typeByString<T> = T extends 'number' ? number : T extends 'string' ? string : T extends 'boolean' ? boolean : T extends 'null' ? null : T extends 'number[]' ? number[] : T extends 'string[]' ? string[] : T extends 'boolean[]' ? boolean[] : any;
const myTypes = ["string", "null"]  as const;
const selected = myTypes[0];
const c : typeByString<typeof selected> = "cool";
const d : typeByString<typeof myTypes[1]> = null;

我认为支持这一点的最简单方法是创建一个将类型名称映射到实际类型的接口。然后你只需要查找它们:

interface LookupType {
number: number
string: string
boolean: boolean
"number[]": number[]
person: Person
}
const type1 = "number";
let myVariable1: LookupType[typeof type1] = 12;
let type2 = "string" as const;
let myVariable2: LookupType[typeof type2] = "foo";
let type3 = 'number[]' as const
let myVariable3: LookupType[typeof type3] = [1,2,3]

这是因为这个接口的键是字符串,即使该字符串恰好与它引用的类型同名。这将是一个比一组分支条件更容易维护的列表。


它还有一个额外的好处,即对不支持的类型进行简单的类型检查

let doesntExist = 'badTypeName' as const
let badVar: LookupType[typeof doesntExist] = 123
// Property 'badTypeName' does not exist on type 'LookupType'.(2339)

游乐场

最新更新