[英]TypeScript type declaration
Can someone explain to me what exactly this declaration means in TypeScript?有人可以向我解释这个声明在 TypeScript 中的确切含义吗? I know that with type and interface I can create new data types.我知道通过类型和接口我可以创建新的数据类型。 But I really can not understand this statement.但我真的无法理解这种说法。
type ParameterizedContext<StateT = DefaultState, CustomT = DefaultContext> = ExtendableContext & {
state: StateT;
} & CustomT;
I found this at https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/koa/index.d.ts我在https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/koa/index.d.ts找到了这个
Thank you,谢谢,
The &
operator allow to create intersection-types . &
运算符允许创建交集类型。 A & B
is a type which is A and B, has all the properties of A and all the properties of B. A & B
是 A 和 B 的类型,具有 A 的所有属性和 B 的所有属性。
In your type, ParameterizedContext
is an ExtendableContext
plus a property called state
of type StateT
plus all the properties of CustomT
在您的类型中, ParameterizedContext
是一个ExtendableContext
加上一个名为state
的CustomT
类型的属性加上StateT
的所有属性
StateT
and CustomT
are generics . StateT
和CustomT
是generics 。 generics allow to reuse type definition by adding parameters. generics 允许通过添加参数来重用类型定义。
StateT
by default is an DefaultState
which is defined as any
. StateT
默认是一个DefaultState
,它被定义为any
。 CustomT
by default is a DefaultContext
which is defined by a Record<string, any>
.默认情况下, CustomT
是一个DefaultContext
,它由Record<string, any>
定义。
ParameterizedContext<StateT = DefaultState, CustomT = DefaultContext>
This is the start of defining a generic type.这是定义泛型类型的开始。 StateT
and CustomT
are placeholders which you can fill in with any type you like, though if you don't fill them in it will use DefaultState
and DefaultContext
. StateT
和CustomT
是占位符,您可以填写任何您喜欢的类型,但如果您不填写它们,它将使用DefaultState
和DefaultContext
。
For example, if you create a ParameterizedContext<{ foo: string }, { bar: number }>
, then StateT
is becomes { foo: string }
everywhere in the type and CustomT
becomes { bar: number }
例如,如果您创建ParameterizedContext<{ foo: string }, { bar: number }>
,则StateT
在类型中的任何位置都变为{ foo: string }
而CustomT
变为{ bar: number }
ExtendableContext & {
state: StateT;
} & CustomT;
This means that it has all of the properties of ExtendableContext, plus a state property who's type is StateT
, plus all of the properties of CustomT
.这意味着它具有 ExtendableContext 的所有属性,以及类型为StateT
的 state 属性,以及CustomT
的所有属性。
So continuing the example from above, if StateT
is { foo: string }
and CustomT
is { bar: number }
, then this type is the following所以继续上面的例子,如果StateT
是{ foo: string }
并且CustomT
是{ bar: number }
,那么这个类型如下
{
// ... imagine all the properties of ExtendableContext being here (i don't know what they are)
state: { foo: string },
bar: number,
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.