[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> {}
原文地址:https://www.cnblogs.com/Answer1215/p/13982705.html