Misc
Five predicates for specific built-in object types.
| Predicate | Quick rule |
|---|---|
isPromise(v) | v instanceof Promise (recognizes subclasses) |
isDate(v) | typeof v === "object" && v instanceof Date |
isGenerator(v) | Object with .next() AND [Symbol.iterator]() === v (duck-typed) |
isFormElement(v) | v instanceof HTMLFormElement |
isFormData(v) | v instanceof FormData |
isPromise
isPromise(Promise.resolve()); // trueisPromise(new Promise((r) => r(1))); // trueisPromise(fetch("/api")); // true
isPromise({ then() {} }); // false (thenable, not a Promise)isPromise(async function () {}()); // true (async fn returns a Promise)isPromise({}); // falseisPromise(null); // false
class MyPromise extends Promise<unknown> {}isPromise(new MyPromise((r) => r(1))); // true (subclasses match via instanceof)isDate
isDate(new Date()); // trueisDate(new Date(0)); // trueisDate(new Date("2024-01-01"));// trueisDate(new Date("not real")); // true (invalid Date is still a Date)
isDate("2024-01-01"); // false (string, not Date)isDate(Date.now()); // false (number)isDate({}); // falseisDate(null); // falseNote: isDate(new Date("invalid")) is true. To check “is it a valid Date instance”:
function isValidDate(v: unknown): v is Date { return isDate(v) && !Number.isNaN((v as Date).getTime());}isGenerator
Duck-typed: an object that has a .next function AND whose [Symbol.iterator]() returns itself (the defining trait of a generator instance).
function* gen() { yield 1; }isGenerator(gen()); // true (generator instance)
isGenerator(gen); // false (the generator FUNCTION, not an instance)isGenerator({}); // falseisGenerator(() => {}); // falseisGenerator("hello"); // falseisGenerator(null); // falseisFormElement (Is.form)
Checks value instanceof HTMLFormElement. Guards on typeof HTMLFormElement === "undefined" so it returns false on the server instead of throwing.
const form = document.createElement("form");isFormElement(form); // trueisFormElement(document.createElement("div")); // falseisFormElement({}); // falseisFormElement(null); // falseAliased as Is.form and Is.formElement — both point at the same function.
isFormData
Checks value instanceof FormData. Throws on the server if FormData is undefined (it isn’t on Node 18+, where FormData is global).
isFormData(new FormData()); // trueisFormData({}); // falseisFormData(null); // falseNotes
isPromise,isDate,isFormElement, andisFormDataall useinstanceof, so subclasses match.isGeneratoris duck-typed and matches generator instances regardless of how they were produced.- All five return a real
false(not the operand) for non-matches — safe to compare with=== falseor!. - For Promise-shaped checks (the thenable protocol — anything with a
.then(onFulfill, onReject)method), usevalue != null && typeof value.then === "function"directly.isPromiseis stricter on purpose.