Contravariant type parameter for flow function?

Viewed 63

I have two (more in reality) types, basically a basetype and a (multiple in reality) extended types. A function I have only operates on the base type parameters - it will only read the object and not update it. However it should accept any form of subtype and not have a problem.

So the function should be contravariant (correct me if I'm wrong I tend to mix those up sadly), I believe by saying the variable is read only it should work right?

type baseTy = {|
    id: number;
|}

type extendedTy = {|
    ...baseTy,
    extra: string,
|}

const dat: extendedTy = {
    id: 1,
    extra: 'test',
}

function getDoubleId(dat: $ReadOnly<baseTy>) {
    return dat.id * 2;
}

function doIt() {
    getDoubleId(dat);
}

However if I try above on flow I get the following error:

Cannot call `getDoubleId` with `dat` bound to `dat` because property `extra` is missing in `baseTy` [1] but exists in `extendedTy` [2]. [prop-missing]

Which seems weird to me: by stating the variable is readonly it should accept any "child" from the base type, right?

I've tried to add $Shape<baseTy> - To "remove" the exact marks around the base type but that has the same error....

0 Answers
Related