简体   繁体   English

typescript 类型不匹配问题

[英]typescript type mismatch issue

I was going through react typescript cheatsheet and one code snippet caught my attention:我正在浏览react typescript 备忘单,一个代码片段引起了我的注意:

export function createCtx<A>(defaultValue: A) {
 type UpdateType = Dispatch<SetStateAction<typeof defaultValue>>;
 const defaultUpdate: UpdateType = () => defaultValue;
 const ctx = createContext({
   state: defaultValue,
   update: defaultUpdate,
 });

 function Provider(props: PropsWithChildren<{}>) {
   const [state, update] = useState(defaultValue);
   return <ctx.Provider value={{ state, update }} {...props} />;
 }
 return [ctx, Provider] as const; // alternatively, [typeof ctx, typeof Provider]
}

the purpose of this function function is to create a context and provider based on the defaultValue passed to the function.此 function function 的目的是根据传递给 function 的defaultValue创建上下文和提供程序。 I have difficulty understanding the first two lines of the function:我很难理解 function 的前两行:

 type UpdateType = Dispatch<SetStateAction<typeof defaultValue>>;
 const defaultUpdate: UpdateType = () => defaultValue;

Dispatch is defined as: Dispatch定义为:

type Dispatch<A> = (value: A) => void;

and SetStateAction as:SetStateAction为:

type SetStateAction<S> = S | ((prevState: S) => S);

this make () => defaultValue not assignable to type UpdateType , How this can possible.这使得() => defaultValue不能分配给类型UpdateType ,这怎么可能。

I let you check this typescript playground to see that there is no problem.我让你检查一下这个typescript操场,看看没有问题。

To elaborate, let's unroll the UpdateType :为了详细说明,让我们展开UpdateType

type DVT = typeof defaultValue;
type UpdateType = (value: DVT | ((prevState: DVT) => DVT) => void;

And the function () => defaultValue;而 function () => defaultValue; has a type:有一个类型:

type FunType = () => DVT;

So first let's consider the return value: void should not accept a return value right?所以首先让我们考虑返回值: void不应该接受返回值对吗? Well not exactly, void does not force a function to not return a value.不完全是, void不会强制 function 不返回值。 It's very common to assign a function that return a value to a type with a void return type.分配 function 将值返回给具有void返回类型的类型是很常见的。

See Assignability of Functions for this and this of course Why are functions returning non-void assignable to function returning void?当然,请参阅函数的可分配性为什么返回非 void 的函数可分配给 function 返回 void? . .

Then the argument value, the function () => defaultValue ignore the arguments so it's safe to use it an UpdateType type.然后参数值 function () => defaultValue忽略 arguments 因此使用UpdateType类型是安全的。 You could have written (value) => defaultValue , but value would be unused, so TypeScript consider it safe (which is).您可以编写(value) => defaultValue ,但value将未被使用,因此 TypeScript 认为它是安全的(这是)。

See Why are functions with fewer parameters assignable to functions that take more parameters?请参阅为什么具有较少参数的函数可以分配给具有更多参数的函数? . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM