# Generic

  • Support the use of generics in the definition of record types, and use them as types in the attribute types.

  • Record types with generics need to be instantiated with actual types before they can be used to declare variable types

  • Supports generics when defining new record types and supports multiple generic parameters

grammar

type RecordName <GenericName1, … > = { PropName: TypeName, … }

E.g:

type G1<T1, T2, T3> = {   -- Here T1, T2, and T3 are generic type variables. Here, a generic type G1 is defined. When specifically used, you can replace T1, T2, and T3 with specific types to generate a new type.
    id: string,
    a: T1,
    b: T2,
    c: T3
}
  • Generic type partial instantiation and type redefinition
  • The record type with generics, you can not use all generic type variables, only replace some of the type variables to generate new generic types

grammar

type RecordName {<GenericName1, … > } = RecordNameExisted { <TypeName1, … >  }

E.g:

type G2<T> = G1<int, T, string>        -- Define a new generic type G2 with a type variable T. This generic type is a new type generated by replacing three types of variables in the G1 generic type with int, T, and string respectively.
type G3 = G2<string>                   -- Define a new type G3, which is a new type generated by replacing type variables in G2 generics with string
  • Generic instantiation refers to replacing type variables in generics with concrete types, such as G2<string> instantiation of G2 generics

  • Generic instantiation can be used directly in the type declaration of variables/function parameters, or it can be used directly in the constructor

E.g:

type G2<T> = { name: string, info: T }
let a1: G2<string> = { name: 'glua', info: 'hello' }
let a2 = G2<int>({ name: 'glua', info: 123 })