headacheCoder
headacheCoder

Reputation: 4613

Extend Object Type and Overwrite Property in Flow

In TypeScript, I am able to do the following:

interface MyObj {
    a: 'foo' | 'bar'
}

interface MyExtObj extends Pick<MyObj, Exclude<keyof MyObj, 'a'>> {
    a: MyObj['a'] | 'baz'
}

const test: MyExtObj = {
    a: 'baz' // Works fine, as well as 'foo' and 'bar'
}

Is it possible to do that with Flow object types and if so, how? The following example fails...

/* @flow */

type MyObj = {
    a: 'foo' | 'bar'
}

type MyExtObj = MyObj & {
    a: $PropertyType<MyObj, 'a'> | 'baz'
}

const test: MyExtObj = {
    a: 'baz' // Cannot assign object literal blah blah ...
}

Upvotes: 2

Views: 686

Answers (2)

Andrew Smith
Andrew Smith

Reputation: 1444

This also works, in case you don't want to make MyObj exact for some reason:

/* @flow */

type MyObj = {
    a: 'foo' | 'bar'
}

type MyExtObj = {|
    ...$Exact<MyObj>,
    a: $PropertyType<MyObj, 'a'> | 'baz'
|}

const test: MyExtObj = {
    a: 'baz' // Cannot assign object literal blah blah ...
}

Upvotes: 1

Alex Savin
Alex Savin

Reputation: 528

Like this?

/* @flow */

type MyObj = {|
    a: 'foo' | 'bar'
|}

type MyExtObj = {|
    ...MyObj,
    a: $PropertyType<MyObj, 'a'> | 'baz'
|}

const test: MyExtObj = {
    a: 'baz' // Cannot assign object literal blah blah ...
}

You can test here

Upvotes: 3

Related Questions