You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flow中$Keys<>类型是什么?相关代码写法是否正确?

Understanding $Keys in Flow and Correct Usage in Switch Statements

Hey there! Since you're just getting started with Flow, React, and redux-observable, let's break down your questions clearly:

What is $Keys in Flow?

$Keys<T> is a built-in utility type in Flow that extracts all the string literal keys from an object type T and turns them into a union type.

For example, if you have a type like this:

type Users = {
  id: string;
  username: string;
  email: string;
};

$Keys<Users> would evaluate to the union type "id" | "username" | "email".

This is super useful because it lets you restrict a variable to only be one of the valid keys of your object type—Flow will throw an error if you try to assign a value that's not a key from T, which helps catch typos or outdated key names early.

Is switch(type: $Keys<Clinic>) written correctly?

Short answer: No, that syntax isn't valid in Flow (or JavaScript, for that matter).

The issue is that you can't add a type annotation directly inside the switch() parentheses. Type annotations in Flow belong on variable declarations, not inline in expressions like that.

Correct Approach

First, declare your type variable with the $Keys<Clinic> annotation, then pass it to the switch statement:

// First define your Clinic type
type Clinic = {
  clinicId: number;
  clinicName: string;
  location: string;
};

// Declare the variable with the $Keys type annotation
const selectedKey: $Keys<Clinic> = "clinicName";

// Now use it in switch
switch (selectedKey) {
  case "clinicId":
    // Handle clinic ID logic
    break;
  case "clinicName":
    // Handle clinic name logic
    break;
  case "location":
    // Handle location logic
    break;
  default:
    // Flow will flag this as unreachable if you cover all keys,
    // but it's safe to include for edge cases
    throw new Error(`Invalid Clinic key: ${selectedKey}`);
}

A big perk here is that if you ever add or remove a key from the Clinic type, Flow will automatically warn you if your switch statement is missing a case (or has an extra one), keeping your code in sync as your types evolve.

内容的提问来源于stack exchange,提问作者sonicmario

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:59:14