gpt4 book ai didi

reactjs - 确保类型 A 扩展了类型 B,它有一个字段是另一个对象的值

转载 作者:搜寻专家 更新时间:2023-10-30 21:57:02 24 4
gpt4 key购买 nike

我想确保类型 A 有一个泛型字段,但该字段的名称由另一个对象的字段值定义。

例如函数:

interface IndexedContext<K extends string, T> {
context: T;
key: K;
}

type TypeB<P, K, T> = {
// this field should be named after IndexedContext[key]
P[K] = T;
}

const Consumer =
<T extends object, K>(context: IndexedContext<K, T>) => <C extends ComponentType<TypeA>, TypeA extends TypeB: C => {
.....
};

TypeA (props) 应该有一个字段,它是 IndexedKey 中字段键的值?因此,当我在 React 组件上使用此装饰器并将 ReactContext 传递给它时,我可以确保 Prop 具有与键相同的字段。

@Consumer({context: MyContext, key: 'myKey'})
class MyClass extends Component<MyProps> {}


interface MyProps {
// compiler should fail if this key is missing.
myKey: // Type of value of MyContext
}

最佳答案

您不需要定义任何额外的 mapped types (例如 TypeB 应该在您的示例中),您可以使用 Record 从字符串文字和字段类型中获取映射类型。

您还需要捕获实例类型而不是构造函数。如果您编写 {context: MyContext, key: 'myKey'}context 将是类 MyContext,因此 T 将被推断为 typeof MyContext 而不是 MyContext。要获取实例类型,您可以键入 context 作为 new (...a:any[]) => T

综合起来:

interface IndexedContext<K extends string, T> {
context: Type<T>;
key: K;
}
type Type<T> = new (...a: any[]) => T

const Consumer =
<T extends object, K extends string>(context: IndexedContext<K, T>) => <C extends ComponentType<Record<K, T>>>(cls: C) => {

};

class MyContext { }
@Consumer({ context: MyContext, key: 'myKey' })
class MyClass extends Component<MyProps> { }


interface MyProps {
// compiler WILL fail if this key is missing.
myKey: MyContext// Type of value of MyContext
}

注意 context 必须分配一个类才能工作,您将无法直接使用接口(interface)或原语。

关于reactjs - 确保类型 A 扩展了类型 B,它有一个字段是另一个对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53375999/

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