Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以在TypeScript严格空检查模式下禁用空和未定义的区分吗?_Typescript_Nullable_Strict_Strictnullchecks - Fatal编程技术网

我可以在TypeScript严格空检查模式下禁用空和未定义的区分吗?

我可以在TypeScript严格空检查模式下禁用空和未定义的区分吗?,typescript,nullable,strict,strictnullchecks,Typescript,Nullable,Strict,Strictnullchecks,我目前正在将大型TypeScript代码库转换为严格的空检查。代码库有许多类型,具有可选成员: interface MyInterface { member1?: number; member2?: string; } 此外,它使用类型Nullable=T | null,并有许多返回null语句 现在我面临着许多编译器错误,这些错误基本上表明T | null不能转换为T | undefined,反之亦然,如本例所示: interface MyInterface { member1?

我目前正在将大型TypeScript代码库转换为严格的空检查。代码库有许多类型,具有可选成员:

interface MyInterface {
  member1?: number;
  member2?: string;
}
此外,它使用类型
Nullable=T | null
,并有许多
返回null
语句

现在我面临着许多编译器错误,这些错误基本上表明
T | null
不能转换为
T | undefined
,反之亦然,如本例所示:

interface MyInterface {
  member1?: number;
  member2?: string;
}

const myFunction = () => {
  return null;
}

const item: MyInterface = {};
item.member1 = myFunction();      // <== can't assign null to undefined
接口MyInterface{
成员1:编号;
member2?:字符串;
}
常量myFunction=()=>{
返回null;
}
常量项:MyInterface={};

item.member1=myFunction();// 我最好写一条评论,但因为我想给你们看一些代码示例,所以我把它作为答案

如果我是你,我会为所有具有可选(弱)属性的接口添加一些包装器

以下是此类包装器的一个示例:


类型MapNullable={
[P in keyof T]:未定义的扩展T[P]?(T[P]| null):T[P]
}
接口MyInterface{
成员1:编号;
member2?:字符串;
}
常量myFunction=()=>{
返回null;
}
常量项:MapNullable={};
item.member1=myFunction();//member1?:数字|空|未定义
MapNullable
迭代所有属性。如果属性是可选的,则只需使用一个以上的类型扩展此属性-
null
,如果属性不是可选的,则保持原样

我知道这不是最好的解决方案,但至少它可以帮助您进行迁移。 一旦迁移,您就可以使类型更加健壮,并摆脱
MapNullable
接口

MapNullable
不是类型的最佳名称,但仍优于
Foo
Bar

我同意@jcalz,我无法想象以其他方式处理未定义的| null

更新

看起来您的代码在TS操场中工作正常。请看

我已禁用了
strictNullChecks
。没有错误

您应该显式地设置函数的返回类型

constmyfunction=():null=>{
返回null;
}

TS版本:4.0.2

我是说,没有?你必须改变你的类型。将
member1?:number
转换为
member1?:number | null
,任何对
null
未定义
的单独引用可能都应更改为union
null |未定义
。如果有人能提出一个答案而不是“不”,我会洗耳恭听,但我认为这是不可能的possible@jcalz如果不可能,这将是对TypeScript的一个很好的补充。在99.9%的情况下,null和undefined之间的区别没有任何用处。很确定这是不可能的。此外,禁用差异化也没有意义,因为它们在JavaScript中实际上是两种不同的类型
null===undefined
将产生
false
,因为它们实际上并不相同,即使它们通常被视为相同。只要不要在你的代码库中使用null,如果你不区分它和未定义的。@pascalpuetz是的,它们在Javascript中是不同的类型。我的观点是,我们可以在TypeScript中启用或禁用严格的空检查。禁用时,我们可以将
null
分配给可选成员(即分配给
number | undefined
),而无需TypeScript说明任何内容。因此,如果没有严格的null检查,TypeScript并不真正关心我是使用
null
还是
undefined
。我的问题是,我们能在不启用这种差异的情况下启用严格的空检查吗?@cheesus您可以随时打开提议这样一个功能,但我不知道它会有什么吸引力。它甚至可能被直接拒绝。谢谢,
MapNullable
似乎就是我想要的。我要试试看。关于您的更新,是的,没有
strictNullChecks
,我的示例是透明的。但我的问题是,如何让它通过
strictNullChecks
进行传输。有时当你深入使用TS时,你可能会忘记最初的问题)