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.
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.
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:
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.
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 −
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With