Reputation: 4760
Consider the following code block
interface Store {
loading: boolean;
}
interface StoreMethod {
(s: Store): Store;
}
export const createStore: StoreMethod = (store) => {
return { ...store, working: false };
}
export const loadStore: StoreMethod = (store) => {
return { loading: true, working: false };
}
I am expecting typescript to throw an error because in the return object is supposed to be Store
which does not have property working
. Am I missing something?
You can check the code in playground here.
Upvotes: 1
Views: 1043
Reputation: 6814
You need to understand that typescript transpiles your code to plain javascript which has no concept of interfaces.
In typescript type A
is compatible with type B
if A
has all of the properties that B
does but A does not have to have the exact number of properties that B has, A
has to at least have those properties that B
does, aka, A
could contain other properties which are not present in B
. So this function
export const loadStore: StoreMethod = (store) => {
return { loading: true, working: false };
}
The returned object clearly has a propert called loading
which satifies the contract your Store
imposes, so the returned object is considered compatible to Store
, if you remove the loading
property from the returned object, typescript will complain.
Interface in typescript is a design artifact, it is not present at runtime.
Upvotes: 4