void Callback Types Accept Any Return Value

Assign functions that return anything to a void-typed callback contract; the value is simply ignored, while a void function cannot fill a typed slot.

TypescriptResilience

Code

typescriptsnippet
21 lines
// void 只约束"调用方忽略返回值":实现里返回什么都合法
type EventHandler = (event: string) => void;

const returnsNumber: EventHandler = (event) => event.length;
const returnsBoolean: EventHandler = (event) => event.startsWith('on');
const returnsVoid: EventHandler = (event) => {
  console.log('handled:', event);
};

// 反向不成立:要求返回 number 的位置不能放 void 函数
function register(handler: (event: string) => number): void {
  console.log('first result:', handler('resize'));
}

register((event) => event.length);

for (const handler of [returnsNumber, returnsBoolean, returnsVoid]) {
  const result = handler('click');
  // result 的类型是 void:契约明确说返回值不该被使用
  console.log('typeof returned value:', typeof result);
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

first result: 6
typeof returned value: number
typeof returned value: boolean
handled: click
typeof returned value: undefined

How the snippet works

void Callback Types Accept Any Return Value is built around the function register.

Iteration happens inside for (const handler of [returnsNumber, returnsBoolean, returnsVoid]) — everything outside it runs once.

Applying it

Entry signature: function register(handler: (event: string)

Look for the handled:, first result:, typeof returned value: prefixes when the file runs; they tie each line to its step.

Statements that matter

const returnsBoolean: EventHandler = (event) => event.startsWith('on');
function register(handler: (event: string) => number): void {
console.log('first result:', handler('resize'));
}
const returnsNumber: EventHandler = (event) => event.length;

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `register` at load time.