简体   繁体   中英

Flow: make a key from an imported object type optional

I want to import a random object from an external module and use their flow type:

export type randomType = {
    a: string,
    b: boolean
}

I want to import the randomType to my library but I want to make b optional

import { randomType } from 'randomModule';
// pseudo flow code:
type shrinkedRandomType = randomType - {b: boolean}
// How can I make this in flow so it equals this?
type shrinkedRandomType = {
    a: string,
    b?: boolean
}
// or even 
type shrinkedRandomType = {
    a: string
}

The spread operator to the rescue!

If you are unfamiliar with the spread operator, look it up on MDN

Otherwise, the way to do it would be as follows:

type randomType = {
    a: string,
    b: boolean
}

type shrinkedRandomType = {
    ...randomType,
    b?: boolean
}

// Perfectly valid
let test:shrinkedRandomType = {
 a: "Hi"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM