本文介绍了TypeScript 忽略类型为 never 的可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不希望将特定函数作为参数传递给另一个函数,但是根据 TypeScript 它是有效的,但是是吗?为什么?

代码示例如下:

函数口语(不?:从不):void {console.log("他说了.");}函数说话(toSay:字符串,口语:(arg1:字符串)=> void):void {console.log("他说:" + toSay);说话(他说话了.");}说话(你好世界.",口语);

因为基本上,TypeScript 说类型 string 可以分配给 type never,因为如果 nope 是让我们说类型 number,TypeScript 会抱怨,因为类型 string 与类型 number 不兼容.

解决方案

简短回答

...根据 TypeScript 它是有效的,但是是吗?为什么?

是的,它是有效的,因为 TypeScript 说类型 never 可以分配给类型 string.这是 打字稿/播放中的一些代码来演示.

从不

的详细信息

基本类型文档 说:

never 类型是每个类型的子类型,并且可以分配给每个类型;但是,没有任何类型是 never 的子类型或可分配给 never(除了 never 本身).

这意味着我们可以将never 分配给string,但不能将string 分配给never.

let arg1: string = (null as never);//有效让 arg2: never = (null as string);//失败

关于您的情况的详细信息

您的 speak 函数有一个名为 spoken 的参数,该函数具有 arg1 类型的 string.这是 spoken 参数本身.

let speakParam: (arg1: string) =>空白;

由于 arg1string 并且 stringnever 的超类型,下面的赋值是有效.

函数口语(不?:从不):void {console.log("他说了.");}口语参数 = 口语;

I don't want a specific function to be passed as a parameter to another function however according to TypeScript it is valid, but is it? and why?

Here's the code example:

function spoken(nope?: never): void {
    console.log("He has spoken.");
}

function speak(toSay: string, spoken: (arg1: string) => void): void {
    console.log("He says: " + toSay);
    spoken("He has spoken.");
}

speak("Hello world.", spoken);

Because basically, TypeScript says type string is assignable to type never, because if nope were of lets say type number, TypeScript would complain because type string isn't compatible to type number.

解决方案

Short Answer

Yes, it is valid, because TypeScript says that type never is assignable to type string. Here is some code in typescript/play to demonstrate.

Details on never

The Basic Types documentation says:

That means we can assign never to string but cannot assign string to never.

let arg1: string = (null as never); // works
let arg2: never = (null as string); // fails

Details on Your Situation

Your speak function has a parameter named spoken, which is a function that has an arg1 parameter of type string. Here is the spoken parameter on its own.

let spokenParam: (arg1: string) => void;

Since arg1 is a string and string is a super-type of never, the following assignment is valid.

function spoken(nope?: never): void {
    console.log("He has spoken.");
}

spokenParam = spoken;

这篇关于TypeScript 忽略类型为 never 的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 11:19