[英]Typescript syntax
I'm new to TypeScript, and working one of my company's repos that uses it heavily. 我是TypeScript的新手,正在使用公司大量使用它的公司回购协议之一。 (We're building a React/Redux app.) I'm familiar with the basic concept of TypeScript Generics, but a particular bit of syntax is befuddling.
(我们正在构建一个React / Redux应用程序。)我熟悉TypeScript泛型的基本概念,但是语法上有一点点令人困惑。 Here's an example of the code in question (it's in a reducer):
这是有问题的代码的示例(在简化程序中):
interface EntityState<Entity> {
entity?: Entity;
status: ApiStatus; // enum
}
interface FieldSummary {
dataType?: string;
// other properties...
}
function singleField(state: EntityState<FieldSummary> = defaultEntityState,
action: ActionTypes) {...}
Would someone be able to explain what EntityState<FieldSummary>
is doing? 有人能够解释
EntityState<FieldSummary>
在做什么吗? If further details are needed just let me know. 如果需要更多详细信息,请告诉我。
It's an example of a generic type argument. 这是泛型类型参数的示例。
interface EntityState<Entity> {
entity?: Entity;
status: ApiStatus;
}
The interface will contain an optional entity?
该接口将包含一个可选
entity?
of a type to be defined later. 类型,稍后再定义。 For now, it has been called
Entity
. 目前,它被称为
Entity
。
When you use this interface, you supply the type, thus: 使用此接口时,请提供类型,从而:
const stringEntity: EntityState<string>;
The property stringEntity.entity
will either be a string
or undefined
(given it is optional). 属性
stringEntity.entity
可以是string
也可以是undefined
(假设它是可选的)。
const numEntity: EntityState<number>;
The property numEntity.entity
will either be a number
or undefined
. numEntity.entity
属性将是number
或undefined
。
And so on. 等等。 The type argument you supply when you use the interface can be any type that satisfies any constraints - in your case, the type parameter is unconstrained.
使用接口时提供的type参数可以是满足任何约束的任何类型-在您的情况下,type参数不受约束。 It means you can re-use an interface because the type is defined later.
这意味着您可以重用接口,因为类型是在以后定义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.