gpt4 book ai didi

Type with unknown number of properties together with a property of type Record(具有未知数量的属性的类型以及类型为Record的属性<字符串,字符串>)

转载 作者:bug小助手 更新时间:2023-10-24 20:46:49 28 4
gpt4 key购买 nike



I'm trying to create a type for a React component. There are two known properties: foo of type string and bar of type Record<string, string>. It also need to accept an unknown number of properties of type string. Getting the type working is no problem but when the component is used, TypeScript is complaining:

我正在尝试为Reaction组件创建一个类型。有两个已知的属性:字符串类型的foo和记录类型的bar<字符串,字符串>。它还需要接受未知数量的字符串类型的属性。让文字正常工作是没有问题的,但当使用组件时,TypeScrip会抱怨:


Type '{ foo: string; bar: Record<string, string>; }' is not assignable to type 'Record<string, string>'.
Property 'bar' is incompatible with index signature.
Type 'Record<string, string>' is not assignable to type 'string'.ts(2322)

The types are declared as following:

这些类型声明如下:


type A = {
foo: string;
bar: Record<string, string>;
};

type B = A & Record<string, string>;

and the component is used like so:

该组件的用法如下:


<Component
foo="name"
bar={{ bar: 'bar' }}
{...{ baz: 'baz' }} // can be any number of unknown properties
/>

更多回答
优秀答案推荐

I am not sure you can do this with a type definition. This index signature is not compatible with the key bar, and although TS allows such constructs, I don't know that they can actually be used directly for type checking.

我不确定您是否可以使用类型定义来做到这一点。这个索引签名与键栏不兼容,尽管TS允许这样的构造,但我不知道它们实际上是否可以直接用于类型检查。


You can use a mapped type to procedurally check the fields though:

不过,您可以使用映射类型按程序检查这些字段:


const Component = <P extends CheckProps<P>>(props: P) => null;

type CheckProps<T> = { [K in keyof T]: K extends keyof A ? A[K] : string }

playground

操场


更多回答

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com