问题描述
我在文档中的许多地方都遇到过Type
关键字.例如,在此处看到 ComponentRef
具有componentType
属性.据说是Type<any>
类型.在进一步搜索中,我找到了关于它的此条目在文档上.它说:调用为ES7装饰器.
I have come across the Type
keyword at many places in the documentation. For example as seen here ComponentRef
has the componentType
property. It is said to be of type Type<any>
. On further searching I find this entry about it on the docs. It says: Invoke as ES7 decorator.
还要查看在github上的源代码中,我找到了这些注释:
Also on looking up the source on github , I find these comments :
/**
* @whatItDoes Represents a type that a Component or other object is instances of.
*
* @description
*
* An example of a `Type` is `MyCustomComponent` class, which in JavaScript is be represented by
* the `MyCustomComponent` constructor function.
但是,我仍然不清楚Type
的作用.我是否缺少基本的东西?
However I am still not clear as to what Type
does. Am I missing something basic ??
推荐答案
根据定义判断:
export const Type = Function;
export interface Type<T> extends Function {
new (...args: any[]): T;
}
Type
只是一个函数. Type<T>
只是在构造(使用参数的任意组合)时创建的T
的某些函数/类型.换句话说,就是类型"定义.请记住,javascript中的类型"(从OO角度)是使用函数表示的.这相当于打字稿中的类,接口等.
Type
is just a function. Type<T>
is just some function/type when constructed (using any combination of arguments), creates a T
. So in other words, a "type" definition. Remember, "types" in javascript (in the OO sense) are represented using functions. And that equates to classes, interfaces and the like in typescript.
鉴于此,以下内容应成立:
Given that, the following should hold:
class Foo {
s: string;
}
class Bar {
s: number;
}
class Biz {
ss: string;
}
class Baz {
s: string;
t: number;
}
let x: Type<{ s: string }>; // x is a type that returns an object
// with an s property of type string
x = Foo; // ok
x = Bar; // error, s is not a string
x = Biz; // error, doesn't contain s property
x = Baz; // ok
x = { s: "foo" }; // haha nice try
这篇关于什么是角度2的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!