如何在TypeScript中将typeof与匿名类型一起使用?
我读了这篇文章,不太了解真实世界的用例,也不太了解typeof的用途。我意识到它们是匿名类型的,但有人对真实世界的用例有什么想法吗 谢谢大家! 以下是文章中的代码,供快速查看如何在TypeScript中将typeof与匿名类型一起使用?,typescript,Typescript,我读了这篇文章,不太了解真实世界的用例,也不太了解typeof的用途。我意识到它们是匿名类型的,但有人对真实世界的用例有什么想法吗 谢谢大家! 以下是文章中的代码,供快速查看 let rectangle1 = { width: 100, height: 200 }; // Obtain the type of `rectangle1` and call it `Rectangle` type Rectangle = typeof rectangle1; let rectangle2: Rec
let rectangle1 = { width: 100, height: 200 };
// Obtain the type of `rectangle1` and call it `Rectangle`
type Rectangle = typeof rectangle1;
let rectangle2: Rectangle;
例如,您只想将正确的类型传递给筛选器, 你可以有这样的结构
const equals:Operator = (value: string, filterValue: string) => {
return value == filterValue;
};
const startsWith:Operator = (value: string, filterValue: string) => {
return value.startsWith(filterValue);
};
const contains:Operator =(value: string, filterValue: string) => {
return !!value.match(filterValue);
};
const endsWith:Operator = (value:string, filterValue: string) => {
return value.endsWith(filterValue);
};
const regex:Operator = (value: string, filterValue: RegExp) => {
return filterValue.test(value);
};
const StringOperatorsMap = {
//equals
'=': equals,
'eq':equals,
'equals':equals,
//contains
'contains':contains,
'*':contains,
//match
'regex': regex,
'match': regex,
're': regex,
//startsWith
'startsWith':startsWith,
'^':startsWith,
//endsWith
'endsWith':endsWith,
'$':endsWith
};
export type StringOperators = keyof typeof StringOperatorsMap;
export const getOperator = (operator: StringOperators) => {
return StringOperatorsMap[operator];
};
这有多个用例 有时,如您的示例中所示,对象已定义为对象文字,您不需要显式定义它的类型,但希望能够以类型安全的方式将其传递给方法:
let rectangle1 = { width: 100, height: 200 };
type Rectangle = typeof rectangle1;
function clone (r: Rectangle ): Rectangle {
return r;
}
或者有时模块导出了一个变量/函数,但没有公开导出,您可以使用typeof
为变量指定一个命名类型,例如,我刚才在回答时使用了它
typeof
即使在没有命名类型的情况下也可以使用,例如,您可以将一个参数的类型定义为与另一个参数的类型相同的类型(避免写入两次类型,特别是如果类型很长)
函数asPromise(值:string | number | Date):Promise{returnnull as any;}
用例是无穷无尽的,这些只是示例。@Tyler并不是这些用例的真正副本,它们是关于具有运行时行为的js
typeof
,这是关于将类型定义为与variable@Tyler这是给类型守卫的,不是我上面描述的:)谢谢。@TitianCernicova Dragomir-hmm,那么也许OP是在寻找泛型而不是typeof?@Tyler,不,他有正确的概念,而且它是有效的。。他只是想找个解释。。
import * as ts from 'typescript' // Import will be elided as long as we only use types from it, so we don't have the compiler code loaded at runtime
type CompilerOptions = typeof ts.parseCommandLine extends (...args: any[])=> infer TResult ?
TResult extends { options: infer TOptions } ? TOptions : never : never;
type TypeAcquisition = typeof ts.parseCommandLine extends (...args: any[])=> infer TResult ?
TResult extends { typeAcquisition?: infer TTypeAcquisition } ? TTypeAcquisition : never : never;
function asPromise(value: string| number| Date) : Promise<typeof value> { return null as any; }