Reputation: 1529
What is the purpose and meaning of defining a type like this..?
type AccountDetails1 = [AccountDetails, ...AccountDetails[]];
Is it equivalent to this union type..?
type AccountDetails2 = AccountDetails | AccountDetails[];
Upvotes: 2
Views: 161
Reputation: 599
type AccountDetails1 = [AccountDetails, ...AccountDetails[]];
It means that variables from type AccountDetails1 must be an array of AccountDetails, and
type AccountDetails2 = AccountDetails | AccountDetails[];
Can be either an AccountDetails or an array of AccountDetails
Upvotes: 1
Reputation: 66123
It simply means that an array with the type of AccountDetails1
must be an array of AccountDetails
with a minimum length of 1. The first part of the tuple indicates that the first element in the array must be of type AccountDetails
, and the second part of the tuple means that the array may contain zero or more AccountDetails
item in the array.
In short:
type AccountDetails1 = [AccountDetails, ...AccountDetails[]];
const arr1: AccountDetails1 = [AccountDetails]; // OK
const arr2: AccountDetails1 = [AccountDetails, AccountDetails]; // OK
const arr3: AccountDetails1 = []; // ERROR
In other words, type AccountDetails2 = AccountDetails | AccountDetails[];
means that it can be either of type AccountDetails
or an array of AccountDetails
with zero or more members:
type AccountDetails2 = AccountDetails | AccountDetails[];
const arr1: AccountDetails2 = [AccountDetails]; // OK
const arr2: AccountDetails2 = [AccountDetails, AccountDetails]; // OK
const arr3: AccountDetails2 = []; // OK
const obj1: AccountDetails2 = AccountDetails; // OK
Upvotes: 3