gpt4 book ai didi

javascript - 什么符号/标记集代表 JavaScript 中不为 null 或未定义的所有内容?

转载 作者:行者123 更新时间:2023-11-28 17:28:27 25 4
gpt4 key购买 nike

我正在为实用函数编写单元测试:

export const isDefined: Function = (value: any): boolean => {
return !(value == null);
};

所以我想验证 Javascript 中所有为 true 的值是否都返回 true。我可以使用一组值来代表所有这些值吗?目前我正在使用集合[{}, "", 1]现在测试如下:

import { isDefined } from "utilities/utilities";
import { expect } from "chai";
import "mocha";

describe("isDefined", () => {
it("should return false for undefined or null arguments", () => {
expect(isDefined(undefined)).to.be.false;
expect(isDefined(null)).to.be.false;
});
it("should return true for non null or undefined arguments", () => {
expect(isDefined({})).to.be.true;
expect(isDefined("")).to.be.true;
expect(isDefined(1)).to.be.true;
});
});

更新

带有类型保护的函数实现 this post

export function isDefined<T>(value: T | null | undefined): value is T {
return value != null
}

最佳答案

关于:

export const isDefined: Function = (value: any): boolean => {
return !!value;
};

或者如果这太神奇了:

export const isDefined: Function = (value: any): boolean => {
return value == true;
};

这也会满足您的测试,但可能不满足您在问题中的定义。

export const isDefined: Function = (value: any): boolean => {
return value !== undefined && value !== null;
};

根据它的名称,这就是我期望该函数执行的操作:

export const isDefined: Function = (value: any): boolean => {
return value !== undefined;
};

编辑

来自信誉良好的来源 (MDN) 的虚假和真实测试用例:

这是官方的 ecmascript 来源:

关于javascript - 什么符号/标记集代表 JavaScript 中不为 null 或未定义的所有内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51003912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com