[Typescript] Using type predicates

 

import { expect, it } from "vitest";
import { Equal, Expect } from "../helpers/type-utils";

export const values = ["a", "b", undefined, "c", undefined];

const filteredValues = values.filter((value): value is string => Boolean(value));

it("Should filter out the undefined values", () => {
  expect(filteredValues).toEqual(["a", "b", "c"]);
});

it('Should be of type "string[]"', () => {
  type test1 = Expect<Equal<typeof filteredValues, string[]>>;
});

 https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates

posted @ 2023-02-10 02:10  Zhentiw  阅读(19)  评论(0编辑  收藏  举报