undeclared-return-type
A function without a declared return type whose result the checker can't read off its returns. An idiomatic rule: reported, as a warning, where the project turns the idiomatic rules on ("safe-ts": { "idiomatic": true }).
Why: SAFE-TS has no type checker. The rules that judge a value by its type (strict-truthiness, must-use-result, no-null-check-for-undefined, number-parse-nan, JSON.stringify in unhandled-failure, prefer-nullish-default, ...) read the type that is written: on the declaration, the parameter, the function's return. Where a function declares none, the checker reads its result off its returns when each is plain (the list is below), and those rules then judge it as if it were declared. What is left, the checker can't see, and every one of those rules is silent about what the function returns. Declaring the type costs one annotation, and brings them back.
❌ Rejected: what await gives isn't read off
✕ Rejectedundeclared-return-type
ts
async function fetchCount(): Promise<number> {
return 1;
}
export async function doubled() {
const count = await fetchCount();
return count * 2;
}✅ Accepted: declared
✓ Accepted0 diagnostics
ts
async function fetchCount(): Promise<number> {
return 1;
}
export async function doubled(): Promise<number> {
const count = await fetchCount();
return count * 2;
}✅ Accepted: read off its body, as if declared
✓ Accepted0 diagnostics
ts
import type { Option } from "@evobug_com/safe-ts-std/result";
export function count(items: readonly string[]) {
return items.length;
}
export const firstLong = (items: readonly string[]) => items.find((item) => item.length > 9);
export function describe(items: readonly string[]): string {
const n = count(items); // a `number`: `if (n)` would be reported by strict-truthiness
const long: Option<string> = firstLong(items);
return n > 0 && long !== undefined ? long : "none";
}✅ Accepted: a composable whose refs and functions are read off
✓ Accepted0 diagnostics
ts
import { computed, ref } from "vue";
export function useCounter(start: number) {
const count = ref(start);
const double = computed(() => count.value * 2);
const increment = (): void => {
count.value++;
};
return { count, double, increment };
}What is read off
A function without a declared return type has the result its returns give, when every one is one of these, or made of these (an arrow's expression body counts as its one return). The type is the one TypeScript infers: a literal keeps its literal type in a const and in a union of returns (return n < 0 ? -1 : 1 is -1 | 1, so if (sign(n)) hides no 0), a lone literal is widened (return "a" is a string), and so is a literal in a let, a property or an element. A test in the repository (crates/safe_ts_core/tests/pairs.rs) holds every form below to that: each is written twice, once with the type TypeScript infers declared (tsc checks that it is), and the two must get the same findings from every rule.
- Literals: a string, template, number, bigint,
true/false,null,undefined. - Operators:
!,typeof,void, unary+, comparisons,===,in,instanceof; arithmetic, unary-, bitwise operators (a number on one side makes-,*,/,&, ... a number),?:,&&,||,??,x as T,x satisfies T,x!. - Bindings: a parameter or variable with a declared type (a function type too: calling
next: () => numbergives anumber), a parameter's default (n = 0is anumber), a variable whose value is plain, the item of afor...ofover a plain list and of an array callback, an import (followed into its file, also a namespace import,export * asand a default export). - Members: of a plain value (
items.length,user.name,rows[0]), of an object literal (helpers.half), of a class of the program or an imported one (a field, a getter, a static member), ofthis, of a field declared with such a class. - Calls of a function whose result is known (declared, or read off by this list): by name, imported, a method of an object literal or a class (also static, also through
this, an instance, or a field typed with the class);err(e)(aResult's error);validate<T>(x)andparseJson<T>(text)(aResult<T, JsonError>);unwrapOr(result, fallback);console.*(nothing);String,Number,Boolean,BigInt,parseInt,parseFloat,isNaN,isFinite,encodeURI*/decodeURI*,Math.*,Number.*,Date.now(),JSON.stringify,Array.isArray,Array.from,String.fromCharCode,Object.keys/entries/values/fromEntries/freeze/is/hasOwn. - Built-in methods of a plain value: of a string,
slice,substring,trim,toLowerCase,toUpperCase,padStart,padEnd,repeat,replace,replaceAll,charAt,concat,normalize,at,codePointAt,indexOf,lastIndexOf,charCodeAt,localeCompare,search,includes,startsWith,endsWith,split; of a number,toFixed,toPrecision,toExponential,toString,toLocaleString; of an array,slice,filter,toSorted,toReversed,sort,reverse,at,find,findLast,pop,shift,join,indexOf,lastIndexOf,findIndex,findLastIndex,push,unshift,includes,some,every,map,flatMap,reducewith a start (reduce(f, 0)is anumber); of aMap,get,has,delete; of aDate,toISOString,toString,toLocale…Stringand the other texts,getTime,valueOfand the otherget…numbers. Afilterorfindover a union is read only for(x) => x !== undefined, the predicate TypeScript infers there; another callback may narrow it in a way the checker can't follow. - Made:
newof a class (a global one, with its type arguments:new Map<string, number>(); one of the program; an imported one), an object or array literal of plain values, a function (its own result is read the same way). - Vue and React:
ref,shallowRef,computed(also with a block body),reactive,readonly,toRef;useState,useRef,useMemo,useCallback. A composable'sreturn { count, double, increment }is read off, anduseCounter(1).count.valueis anumberto every rule.
A return of anything else stops the reading: the result is unknown, not guessed. That is await, a call of a package's function (useTask, open) or of a value of another kind, a method the list doesn't name (text.match(/a/)), a tagged template, a class expression, JSX. So is a generic function (its result depends on its type arguments), a function that returns its own call, directly or through others (TypeScript infers any there), an overloaded one, one assigned again later, a generator, and a body whose end TypeScript may know is never reached when the checker can't (a switch without default whose cases all return, a last statement like panic(...)).
Not reported
- A type from where the function is written: an argument (
items.map((x) => ...),useEffect(() => ...), JSXonClick={() => ...}), a variable, field, property or parameter with a type (also a parameter's default), an assignment (el.onclick = () => ...),as/satisfies, a function returned from one typed that way, and an object or array literal in any of those places. A function passed once by a name nothing else reads (const onLoad = () => ...; load(onLoad)) is typed by the argument it is, as written there would be. - Nothing returned: no
returnwith a value (or an arrow whose body isvoid ...). - One test: a body that is a single test (
return typeof x === "string",x => x !== undefined && x.ok,isUser(x)). TypeScript infers a type predicate from it only while no return type is written, andno-type-predicatesends a hand-written predicate to exactly that form. - A component: every value returned is JSX (or
null), also a list of it (items.map((item) => <li>...</li>)): only React reads it. - Test files (what their helpers return goes to assertions), JavaScript files (they can't declare a type), constructors, setters, declarations without a body.
Quick fix: Declare the return type when every return names a type the file can write: a primitive by its kind, a binding's or field's declared type, x as T, new C(...) of a class without type parameters, undefined where the end is reached, inside Promise<...> for an async function.
TypeScript's and oxlint's options
isolatedDeclarations(TypeScript 5.5) requires a type on every exported declaration a.d.tscan't be written without: every exported function's return type, also where it is obvious, every exportedconstthat isn't a literal, and it needsdeclarationon. It says nothing about the functions a module keeps to itself, where most of the values these rules judge are made. Worth it for a package that publishes declarations; it doesn't replace this rule.- oxlint's
typescript/explicit-function-return-typeasks for a return type on every function, also one whose result is plain (return items.length), and on a single test, where writing: booleandrops the predicate TypeScript infers (and writingx is Tisno-type-predicate).typescript/explicit-module-boundary-typesasks only at exports, likeisolatedDeclarations. Neither knows what the checker reads off, which aliases it opens, or that a callback is typed by where it is written as SAFE-TS sees it.
This rule asks only where the checker is blind, and is checked against what it actually reads.
What the rule can't see: whether a function's result matters: it asks for every unknown result, also of a function whose value only a framework reads. The checker doesn't read a package's declarations, so a result made by a package's function (also one of SAFE-TS's own, like useTask) is unknown, though TypeScript knows it; so is a result whose declared type in the chain is one the checker doesn't open (a conditional or mapped type).