我有一个将存储数据的对象.我有一个UserPrompt个类型、 node 和边的对象(来自Reactflow库).

我希望UserPrompt类型的node_id只接受已经存在于我的‘Nodes’对象中的id.这可以在Typescript 中完成吗?

例如: 如果在我的nodes对象中只有一个id:5的 node ,UserPrompt将不接受3.

代码:

'use client';

import { Edge, Node, NodeProps, useEdges, useNodes } from 'reactflow';
import { Button } from './ui/button';

type UserPrompt = {
  id: number;
  text: string;
  node_id: NodeProps['id'];
};

type SessionObject = {
  nodes: Node<unknown>[];
  edges?: Edge<unknown>[];
  prompts?: UserPrompt[];
};

export default function SaveSessionButton() {
  //TODO: save nodes, edges, user's prompts!
  //TODO: don't save single chat node.
  const nodes = useNodes();
  const edges = useEdges();

  function handleOnClick() {
    const obj: SessionObject = {} as SessionObject;
    obj['nodes'] = nodes;
    obj['edges'] = edges;
    console.log(obj);
  }

  return <Button onClick={handleOnClick}>Save session</Button>;
}

推荐答案

首先,默认情况下,Typescript不能在运行时进行类型判断.这(或某种程度上)可以通过一些第三方库来实现,但这实际上不是您所需要的.

您在这里需要的是一个函数,它将验证输入,并允许在输入不正确的情况下继续操作或抛出错误.如何实施它有多种 Select . 让我们看一个简单的方法示例,该方法在node_id正确的情况下生成正确的对象:

const makePrompt = (obj: SessionObject, id: number, text: string, node_id: NodeProps['id']): UserPrompt => {
    const nodes = obj['nodes'];
    const isValid = nodes.some(n => n.id === node_id);
    if (!isValid) { 
        throw new Error('Node does not exist!')
    }
    return { id, text, node_id }
}

// then somewhere in the code:
const prompt = makePrompt(session, 123, 'hello', 5);

此外,您不需要在那里传递整个会话对象,只需使用 node 列表即可.我在示例中使用了它,以使它更清楚.

基本上,您也可以在现有代码中添加isValid判断,避免创建单独的函数.然而,有一个专用的方法来验证和对象生成是更方便和方便,特别是如果有多个放置在你需要UserPrompt个对象.

Typescript相关问答推荐

替换类型脚本类型中的多个特定字符串

具有映射返回类型的通用设置实用程序

动态判断TypScript对象是否具有不带自定义类型保护的键

带有联合参数的静态大小数组

如何判断输入是否是TypeScript中的品牌类型?

如何访问Content UI的DatePicker/中的sx props of year picker?'<>

如何在使用`Next—intl`和`next/link`时导航

Vue3 Uncaught SyntaxError:每当我重新加载页面时,浏览器控制台中会出现无效或意外的令牌

Angular:ngx-echart 5.2.2与Angular 9集成错误:NG 8002:无法绑定到选项,因为它不是div的已知属性'

笛卡尔产品类型

刷新页面时,TypeScrip Redux丢失状态

APP_INITIALIZER在继续到其他Provider 之前未解析promise

编译TypeScrip项目的一部分导致错误

Angular 16将独立组件作为对话框加载,而不进行布线或预加载

有没有一种更好的方法来存储内存中的数据,而不是在类型脚本中使用数组和基于索引的函数?

如何使用IsEqual创建断言类型相等的实用程序

为什么TS条件返回要求不明确的强制转换而不是精确的强制转换?

Typescript 是否可以区分泛型参数 void?

如何使用 runInInjectionContext 中的参数测试功能性路由防护

元组解释