Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you define an array of Partials in TypeScript?

For instance,

type User = {
  first_name: string,
  last_name: string,
  notes: string
}

Which of the following would work?

const users:Partial<User>[] = [{first_name: "Name"}]; // A

const users:Partial<User[]> = [{first_name: "Name"}]; // B

const users:[Partial<User>] = [{first_name: "Name"}]; // C

Weirdly, all of these appear to be valid TypeScript at compile time.

Thanks in advance.

like image 450
sambecker Avatar asked Aug 25 '18 23:08

sambecker


People also ask

What is partial type in typescript?

The Partial type is one of the utility types in TypeScript. You can use the Partial type to represent a subsets of the type variable you pass to it. In an application that communicates with a REST API you ofter find yourself writing interfaces to represent a resource you want to create.

What is an array in typescript?

Thumbs up for a well-named interface. An array is a special type of data type which can store multiple values of different data types sequentially using a special syntax. TypeScript supports arrays, similar to JavaScript. There are two ways to declare an array:

Why do we use partial types in Java?

Besides, it will prevent from enforcing property values in certain types. That’s when the partial type becomes useful as it makes all these properties optional without the need of modifying the requirement of the properties of the type like in the following example.

How to infer the type of an array in JavaScript?

The type of such an array is inferred from the data type of the array’s first element during initialization. For example, a declaration like − var numlist:number [] = [2,4,6,8] will create an array as given below −


2 Answers

The proper way is

const users:Partial<User>[] = [{first_name: "Name"}];

Partial<User[]> means that it has some of Array properties.

[Partial<User>] means that it's an array of partial User with 1 element.

Weirdly, all of these appear to be valid TypeScript at compile time

The syntax is valid but types aren't. It's expected that Partial<User[]> causes an error because types are incompatible.

like image 66
Estus Flask Avatar answered Oct 23 '22 23:10

Estus Flask


Option A gives you an array containing Partials:

const users:Partial<User>[] = [{first_name: "Name"}]; // A

If it helps you understand, think about how you would define an array of Partials if the type weren't generic. That would be Partial[].

If you remove the generic type from option B, you'd get a single Partial instead of an array.

Option C is a tuple rather than an array.

like image 22
Josh Tynjala Avatar answered Oct 23 '22 22:10

Josh Tynjala