一个相似的例子,我们可能想把泛型参数当作整个接口的一个参数。 这样我们就能清楚的知道使用的具体是哪个泛型类型(比如:Dictionary<string>而不只是Dictionary)。 这样接口里的其它成员也能知道这个参数的类型了。 interfaceGenericIdentityFn<T>{(arg:T):T;}functionidentity<T>(arg:T):T{returnarg;}letmyIdentity:...
这样我们就能清楚的知道使用的具体是哪个泛型类型(比如:Dictionary<string>而不只是Dictionary)。这样接口里的其它成员也能知道这个参数的类型了。 interface GenericIdentityFn<T>{ (arg: T): T; }functionidentity<T>(arg: T): T {returnarg; } let myIdentity: GenericIdentityFn<number> = identity; 注意,我...
一个相似的例子,我们可能想把泛型参数当作整个接口的一个参数。这样我们就能清楚的知道使用的具体是那个泛型类型(比如:Dictionary<string>而不是Dictionary)。这样接口里的其它成员也能知道这个参数的类型了。 interfaceGenericIdentityFn<T>{(arg:T):T;}functionidentity<T>(arg:T):T{returnarg;}letmyIdentity:Generi...
remove(key: string):void; containsKey(key: string): bool; keys(): string[]; values(): any[]; } class Dictionary { _keys: string[]=newstring[]; _values: any[]=newany[]; constructor(init: { key: string; value: any; }[]) {for(varx = 0; x < init.length; x++) {this[init...
type StrDict = Dictionary<string> type DictMember<T>= T extends Dictionary<inferV>? V : never type StrDictMember = DictMember<StrDict>// string 1. 2. 3. 4. 5. 6. 7. 8. 在上面示例中,当类型 T 满足 T extends Dictionary 约束时,我们会使用 infer...
可索引类型(Indexable Types) 是描述把 Object 当作 Dictionary 使用的时候的类型。 typeAnimal={name:stringage:number}typeFoo={[key:string]:Animal;}consta:Foo={};a['foo']={name:'foo',age:2,};typeReadonlyFoo={readonly[key:string]:Animal;};constb:ReadonlyFoo={foo:{name:'foo',age:2,}...
/*** Dictionary of string, value pairs*/typeDictionary<T>={[key:string]:T} [key: string]is a very handy trick in general. You can also modify dictionary fields withReadonlyor make them optional or Omit them, etc. There also exist helper type libraries: ...
interfacePerson{readonlyname:string;age: number;}constjohn: Readonly<Person> = { name:'John', age:30};john.age =31;// Error: Cannot assign to 'age' because it is a read-only property. 在此示例中,age 属性可以修改,但 name 属性是只...
interfaceDictionary<T> {[index:string]: T;}; interfaceNumericDictionary<T> {[index:number]: T;}; constdata:Dictionary<number> = {a:3,b:4} 9. 用 const enum 维护 const 表 Use objects to maintain constsconstTODO_STATUS {TODO:'TODO',DONE:'DONE'...
interfaceDictionary<T>{[key:string]:T;}constportNumbers:Dictionary<number>={};// OKportNumbers["http"]=80;// Error: Property 'http' does not exist on type 'Dictionary<number>'.portNumbers.http=80; TypeScript 2.2 取消了这个限制。现在可以使用[]或.符号访问属性。在许多情况下,不再需要像这样...