简体   繁体   English

TypeScript 型号声明

[英]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加上一个名为stateCustomT类型的属性加上StateT的所有属性

StateT and CustomT are generics . StateTCustomTgenerics 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 . StateTCustomT是占位符,您可以填写任何您喜欢的类型,但如果您不填写它们,它将使用DefaultStateDefaultContext

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM