我读了这个article,我不太了解真实世界的用例以及我可以使用的typeof。我意识到他们是匿名类型,但有没有人对现实世界的用例有任何想法?
谢谢!
以下是文章中用于快速查看的代码。
let rectangle1 = { width: 100, height: 200 };
// Obtain the type of `rectangle1` and call it `Rectangle`
type Rectangle = typeof rectangle1;
let rectangle2: Rectangle;
答案 0 :(得分:1)
有多种用例。
有时在您的示例中,对象已经被定义为对象文字,并且您不必为其明确定义类型,但您确实希望能够以类型安全的方式将对象传递给方法:
let rectangle1 = { width: 100, height: 200 };
type Rectangle = typeof rectangle1;
function clone (r: Rectangle ): Rectangle {
return r;
}
或者有时模块导出的变量/函数但未公开导出,您可以使用typeof
为变量命名类型,例如,我只是在{{3}中使用它回答
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;
即使没有命名类型,也可以使用 typeof
,例如,您可以将参数的类型定义为与另一个参数的类型相同(避免两次写入类型,特别是如果它很长)
function asPromise(value: string| number| Date) : Promise<typeof value> { return null as any; }
用例是无穷无尽的,这些仅仅是一些例子。
答案 1 :(得分:0)
例如,您只希望传递适当的类型进行过滤, 你可能有这样的结构。
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];
};