SWeko SWeko - 1 year ago 77
TypeScript Question

Difference beetween an array-of-type definition and type-in-array definition

I have two types defined using a similar syntax, one as an array of a specified type, and the other as the specified type in an array (Yes, those two sound exactly the same). Their definitions are:

export type First = [{
name: string,
address: string

export type Second = {
name: string,
address: string

I thought that these types are equivalent, as I can initialize them with the same data:

let first : First = [{name:"First", address: "First Street"}];
let second: Second = [{name:"Second", address: "Second Street"}];

and I can even assign

second = first

and it works. However when I try

first = second

I get an error:

error TS2322: Type '{ name: string; address: string; }[]' is not
assignable to type '[{ name: string; address: string; }]'.

Property '0' is missing in type '{ name: string; address: string; }[]'.

This has actually been in my code-base for a while now, and I haven't detected it since all of the assignments went the legal way, and I've only now used it the other way around. Can anyone explain what is the difference between the two type definitions?

Answer Source

Type [string] is tuple type that represents an array with a single string element (at index 0). Type string[] is an array type that represents an array with any number of strings.

So [string] is a subset of string[] and that's why you can assign value with type [string] to variable of type string[] but not the other way.

However, you should be able to do type assertion using <Type> or as Type for the assignment if you know for sure it is correct.

let singleStrArray: [string] = ['foo'];
let strArray: string[] = ['bar'];

singleStrArray = strArray as [string];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download