且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Typescript编译器永远不会错误:键入'string |数字"不能分配给“从不"类型.不能将类型“字符串"分配给类型“从不"

更新时间:2022-11-30 11:44:42

该错误怎么办,这是因为 Obj的关键字可能是'a'类型为 number string 的"b" .在表达式 obj [key] 中,编译器不知道属性类型,它也可能是 number string ,因此不允许这样的任务.此处是相同的问题.您可以在此处中找到说明,请参见修复将不正确的内容写入索引访问类型.

What about the error, it's because keyof Obj might be "a" or "b" which have type number or string. In the expression obj[key] the compiler doesn't know the property type, it might be number or string as well, so it disallows such assignment. Here is the same question. And you can find the explanation here, see Fixes to unsound writes to indexed access types.

对于通用函数, K扩展了Obj的键表示 K 类型可以是"a" "b'" 也是如此,但是当您调用函数 fn("a",2)时,您会隐式地将 K 设置为"a".,编译器从第一个参数推断 K 类型.因此,现在,在调用上下文中, key 具有"a" 类型,而 Obj [K] number ,因此分配变得正确.

In case of the generic function K extends keyof Obj means that K type can be "a" or "b" as well, but when you call the function fn("a", 2) you implicitly set K to "a", the compiler infers K type from the first argument. So now, inside the call context key has "a" type and Obj[K] is number, hence the assignment becomes correct.

我只是试图向我的妻子(不是程序员)解释这种区别:)我认为这也可能有帮助:

I just tried to explain the difference to my wife, who isn't a programmer :) I think it might be helpfull too:

常用功能:假设您正在吃蛋糕,但闭着眼睛.您知道这可能是樱桃蛋糕或香蕉蛋糕.您喜欢这种口味,但不能说多么美味的香蕉蛋糕!"因为您不确定这是香蕉蛋糕.

Usual function: Lets imagine you are eating a cake but your eyes are closed. You know that it might be a cherry cake or a banana cake. You like the taste but you cannot say "What a delicious banana cake!" because you are not sure that it's a banana cake.

通用功能:在这种情况下,您睁开了眼睛,可以选择要吃的蛋糕,但仍然有两种选择:樱桃或香蕉.现在,如果您选择并品尝了香蕉蛋糕,则可以说多么美味的香蕉蛋糕!".

Generic function: In this case you eyes are open and you can choose the cake you want to eat, but you still have two choices: cherry or banana. Now, if you've chosen the banana cake and tasted it, you can say "What a delicious banana cake!".