[Typescript v4] Tuple Types && Recursive types

...T:

type Foo<T extends any[]> = [boolean, ...T, boolean]

In previous typescript version, you can only put '...T' to the last element of array. Put now you can also put it in the middle.

 

Labeld types in array:

type Address = [
    streetNumber: number,
    city: string,
    state: string,
    postal: number
]

function printAddress(...address: Address) {}

 

Recursive type alias:

Old way to do it, for example:

type JSONValue = 
    | string
    | number
    | boolean
    | null
    | JSONArray
    | JSONObject;

interface JSONObject {
    [k: string]: JSONValue
}

interface JSONArray extends Array<JSONValue> {}

We have to define JSONValue first as type, then use it inside interface of JSONObject.

 

In typescript v4, we can do:

type JSONValue = 
    | string
    | number
    | boolean
    | null
    | JSONValue[]
    | {
         [k: string]: JSONValue
      };

interface JSONArray extends Array<JSONValue> {}

 

posted @ 2020-11-15 22:19  Zhentiw  阅读(117)  评论(0编辑  收藏  举报