Add isDefined

This commit is contained in:
Simon Warta 2022-10-09 18:28:40 +02:00
parent 8170471333
commit 63961f79dc
5 changed files with 33 additions and 7 deletions

View File

@ -6,6 +6,11 @@ and this project adheres to
## [Unreleased]
### Added
- @cosmjs/utils: Add `isDefined` which checks for `undefined` in a
TypeScript-friendly way.
## [0.29.1] - 2022-10-09
### Changed

View File

@ -4,7 +4,7 @@ import {
SigningStargateClient,
StargateClient,
} from "@cosmjs/stargate";
import { sleep } from "@cosmjs/utils";
import { isDefined, sleep } from "@cosmjs/utils";
import * as constants from "./constants";
import { debugAccount, logAccountsState, logSendJob } from "./debugging";
@ -13,10 +13,6 @@ import { createClients, createWallets } from "./profile";
import { TokenConfiguration, TokenManager } from "./tokenmanager";
import { MinimalAccount, SendJob } from "./types";
function isDefined<X>(value: X | undefined): value is X {
return value !== undefined;
}
export class Faucet {
public static async make(
apiUrl: string,

View File

@ -1,4 +1,4 @@
export { arrayContentEquals, arrayContentStartsWith } from "./arrays";
export { assert, assertDefined, assertDefinedAndNotNull } from "./assert";
export { sleep } from "./sleep";
export { isNonNullObject, isUint8Array } from "./typechecks";
export { isDefined, isNonNullObject, isUint8Array } from "./typechecks";

View File

@ -1,4 +1,4 @@
import { isNonNullObject, isUint8Array } from "./typechecks";
import { isDefined, isNonNullObject, isUint8Array } from "./typechecks";
describe("typechecks", () => {
describe("isNonNullObject", () => {
@ -55,4 +55,19 @@ describe("typechecks", () => {
expect(isUint8Array(new Uint16Array())).toEqual(false);
});
});
describe("isDefined", () => {
it("works", () => {
expect(isDefined("a")).toEqual(true);
expect(isDefined(1234)).toEqual(true);
expect(isDefined(null)).toEqual(true);
expect(isDefined(undefined)).toEqual(false);
});
it("narrows type of list", () => {
const a = ["one", undefined, "two", "three", undefined];
const b: string[] = a.filter(isDefined);
expect(b).toEqual(["one", "two", "three"]);
});
});
});

View File

@ -30,3 +30,13 @@ export function isUint8Array(data: unknown): data is Uint8Array {
return true;
}
/**
* Checks if input is not undefined in a TypeScript-friendly way.
*
* This is convenient to use in e.g. `Array.filter` as it will convert
* the type of a `Array<Foo | undefined>` to `Array<Foo>`.
*/
export function isDefined<X>(value: X | undefined): value is X {
return value !== undefined;
}