我是打字稿的新手,我定义了一些接口,如下所示:
interface A {
toRemove: string;
key1: "this1";
key2: number;
}
interface B {
toRemove: string;
key1: "this2";
key3: string;
}
Run Code Online (Sandbox Code Playgroud)
以及两个接口的联合:
type C = A|B;
Run Code Online (Sandbox Code Playgroud)
我想要做的是toRemove通过 C 从两个接口中删除密钥,如下所示:
type CC = Omit<A, "toRemove">|Omit<B, "toRemove">;
Run Code Online (Sandbox Code Playgroud)
但不必从两个接口中省略密钥。这将是理想的:
type CC = Omit<C, "toRemove">;
Run Code Online (Sandbox Code Playgroud)
但是,不幸的是,CC将是 type Pick<A|B, "key1">,key1两个接口中都存在的键在哪里。
从本质上讲,我想要实现的是一种要转换的“功能”:
A1|A2|...|An
Run Code Online (Sandbox Code Playgroud)
进入:
Omit<A1, K keyof A1>|Omit<A1, K keyof A2>|...|Omit<An, K keyof An>
Run Code Online (Sandbox Code Playgroud)
我遇到了这个答案/sf/answers/3940847151/,我有一种感觉,我需要的部分就在那里,但我真的不明白该代码中发生了什么。
我有一个组件,它根据特定属性呈现不同的元素,称为type. 它可以有这样的类型定义:
interface CommonProps {
size: 'lg' | 'md' | 'sm';
}
interface SelectInputProps extends CommonProps {
type: 'select';
options: readonly Option[];
selected: string;
}
interface TextInputProps extends CommonProps {
type: 'text';
value: string;
};
type InputProps = (SelectInputProps | TextInputProps) & ExtraProps;
function Field(props: InputProps): JSX.Element;
Run Code Online (Sandbox Code Playgroud)
现在在我自己的组件中,我将访问该组件的属性,如下所示:
import { ComponentProps } from 'react';
type FieldProps = ComponentProps<typeof Field>;
function MySpecialField(props: FieldProps) {
if (props.type === 'select') {
// this works
const { options, selected } = props; …Run Code Online (Sandbox Code Playgroud) 我正在创建一个包装函数,它将refs属性传递给send函数,如下所示。用于创建我的状态机的事件类型被定义为基本接口{ refs: NodeRefs }和可能的事件对象的联合之间的交集,例如{ type: "EVENT_1" } | { type: "EVENT_2", context: MyContextType }。
包装函数(useMachine在示例代码中)应该返回更新后的send函数,该函数需要一个refs省略键的事件对象。Omit当尝试将我的发送函数与联合类型中的任何非共享属性一起使用时,使用此处会导致错误,并且我并不 100% 清楚为什么或如何以不同的方式执行此操作。
enum States {
Unchecked = "UNCHECKED",
Checked = "CHECKED",
Mixed = "MIXED"
}
enum Events {
Toggle = "TOGGLE",
Set = "SET",
UpdateContext = "UPDATE_CONTEXT"
}
// Events for the state machine will be a union type a la TEvent, but all events
// will need a …Run Code Online (Sandbox Code Playgroud)