L
L
lavezzi12021-05-24 17:58:50
typescript
lavezzi1, 2021-05-24 17:58:50

Why is there no error when assigning an array from other interfaces?

Hello. Completed a beginner course on TS and started implementing Vue 3 into a project .

There is a REST API function that pulls the view data:{ meta, volumes }

export const getVolumes = (
  params: RequestMeta,
): Promise<{ meta: RequestMeta, volumes: Volume[] }> => request({
  url: '/volumes/',
  params,
});


Further on the data page looks like this:

data() {
  return {
    volumes: [] as Array<Volume>,
  };
}


And here is the most interesting thing, we pull the data and put it in the previously specified array:

methods: {
  fetchVolumes() {
    getVolumes().then((data) => {
        this.volumes = data.volumes;
    });
  }
}


Everything works great, but ! If I change the API function from getVolumes() to getSnapshots() and put in this.volumes = data.snapshots , an array of Snapshot types , then there is no error. Why is that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-05-24
@lavezzi1

In ts, structural typing. This can happen if the Snapshot is structurally within the Volume type.
Those. This is how the types are interchangeable:

interface Volume {
 id: number;
 volume?: string;
}

interface Snapshot {
 id: number;
 snapshot?: string;
}
And so no:
interface Volume {
 id: number;
 volume: string;
}

interface Snapshot {
 id: number;
 snapshot: string;
}

And so no:
interface Volume {
 id?: number;
}

interface Snapshot {
 id?: string;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question