Flow: Override class instance types

Created on 14 Sep 2017  路  2Comments  路  Source: facebook/flow

This is valid Typescript code, I would expect Flow to work in the same way.

Typescript
https://www.typescriptlang.org/play/index.html#src=class%20One%20%7B%20%0D%0A%20%20%20%20foo%3A%20%7Bone%3A%20string%7D%0D%0A%7D%0D%0A%0D%0Aclass%20Two%20extends%20One%20%7B%20%0D%0A%20%20%20%20foo%3A%20%7Bone%3A%20string%2C%20two%3A%20string%7D%0D%0A%7D

class One { 
    foo: {one: string}
}

class Two extends One { 
    foo: {one: string, two: string}
}

Flow

https://flow.org/try/#0PTAEAEDMBsHsHcBQiDG0CGBnToDyA7AU1AG9RFRLRJZYAuU2IhzAFwCcBLfAcwF9EA1BmygAKvFihCAD1aF8AExwFiZClRr1GzUGy68ANKFaSWHbv0FA

// @flow

class One { 
    foo: {one: string}
}

class Two extends One { 
    foo: {one: string, two: string}
}

// 8:     foo: {one: string, two: string}            
//             ^ property `two`. Property not found in
// 4:     foo: {one: string}            
//             ^ object type

All 2 comments

This is expected, and indeed a major selling point for flow. Typescript does not implement variance checking for generics, but flow does.

The reason this isn鈥檛 safe is this: imagine you write a function that takes a One as an argument. It sets the foo property of that argument to an object with a one property but no two property. What should the type checker say? If you pass in a One, this is safe. But if you pass in a Two, which is a subtype of One, then this isn鈥檛 safe, because you鈥檒l be setting the Two instance to have a foo without the property two. Therefore this code is not type safe because a runtime function call may violate the type of a Two.

Understanding all the details of variance is tricky, and probably not worth going into right here. The flow docs have some explanation of variance which should be helpful.

Thanks for clearing that up @asolove

It's a feature not a bug 馃憤

cjbrqk1wcaasdvu1

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jamiebuilds picture jamiebuilds  路  3Comments

Beingbook picture Beingbook  路  3Comments

marcelbeumer picture marcelbeumer  路  3Comments

philikon picture philikon  路  3Comments

ctrlplusb picture ctrlplusb  路  3Comments