Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,563 questions

56,781 answers

573 users

How to use a function object in TypeScript

7 Answers

0 votes
/*
=====================================================
TITLE: Basic Function Object in TypeScript
=====================================================

A function is an object that can be assigned to
variables and invoked through those variables.

TypeScript allows us to specify parameter and
return types for better type safety.
*/

// Best Practices:

// Prefer explicit function types for public APIs.
// Use type aliases for reusable signatures.
// Use callable interfaces when functions need
// additional properties or methods.
// Use closures for private state.
// Prefer read-only metadata where possible.
// Use const for function references.
// Keep functions focused on a single responsibility.
// Avoid using any unless absolutely necessary.

function greet(name: string): string {
    return `Hello, ${name}!`;
}

// Store the function in another variable.
const sayHello: (name: string) => string = greet;

console.log(sayHello("Cora"));

// Functions are objects and expose metadata.
console.log("Function name:", greet.name);
console.log("Parameter count:", greet.length);



/*
run:

Hello, Cora!
Function name: greet
Parameter count: 1

*/

 



answered 5 days ago by avibootz
edited 5 days ago by avibootz
0 votes
/*
=====================================================
TITLE: Function Type Alias
=====================================================

A type alias helps document intent and improves
readability when a function signature is reused.
*/

type MathOperation = (a: number, b: number) => number;

const add: MathOperation = (a, b) => a + b;
const multiply: MathOperation = (a, b) => a * b;

console.log(add(10, 5));
console.log(multiply(10, 5))



/*
run:

15
50

*/

 



answered 5 days ago by avibootz
0 votes
// Passing a Function Object to Another Function

// ==================================================
// Title: Higher-Order Function
// ==================================================
//
// A higher-order function accepts another function
// as an argument.
//

type Operation = (a: number, b: number) => number;

function calculate(
    a: number,
    b: number,
    operation: Operation
): number {
    return operation(a, b);
}

const add: Operation = (x, y) => x + y;
const multiply: Operation = (x, y) => x * y;

console.log(calculate(10, 5, add));
console.log(calculate(10, 5, multiply));



/*
run:

15
50

*/

 



answered 5 days ago by avibootz
0 votes
// Returning a Function Object

// ==================================================
// Title: Function Factory
// ==================================================
//
// Functions can create and return other functions.
// The returned function remembers data from the
// surrounding scope through closure.
//

function createMultiplier(
    factor: number
): (value: number) => number {

    return (value: number): number => {
        return value * factor;
    };
}

const double = createMultiplier(2);
const triple = createMultiplier(3);

console.log(double(10));
console.log(triple(10));



/*
run:

20
30

*/

 



answered 5 days ago by avibootz
0 votes
// Function Object with Metadata

// ==================================================
// Title: Function Object with Metadata
// ==================================================
//
// A function object can have additional properties.
//
// An interface describes both the callable signature
// and the attached metadata.
//

interface NamedFunction {
    (name: string): string;

    readonly description: string;
    readonly version: string;
}

function createGreetingFunction(): NamedFunction {

    const fn = ((name: string): string => {
        return `Welcome, ${name}!`;
    }) as NamedFunction;

    Object.defineProperties(fn, {
        description: {
            value: "Produces greeting messages",
            writable: false
        },
        version: {
            value: "1.0.0",
            writable: false
        }
    });

    return fn;
}

const greet = createGreetingFunction();

console.log(greet("Cora"));
console.log(greet.description);
console.log(greet.version);



/*
run:

Welcome, Cora!
Produces greeting messages
1.0.0

*/

 



answered 5 days ago by avibootz
0 votes
// ==================================================
// Title: Stateful Function Object
// ==================================================
//
// A function object can maintain private state
// using closures while exposing behavior through
// attached methods.
//

interface Counter {
    (): number;
    reset(): void;
}

function createCounter(): Counter {

    let count = 0;

    const counter = (() => {
        count += 1;
        return count;
    }) as Counter;

    counter.reset = (): void => {
        count = 0;
    };

    return counter;
}

const counter = createCounter();

console.log(counter());
console.log(counter());
console.log(counter());

counter.reset();

console.log(counter());



/*
run:

1
2
3
1

*/

 



answered 5 days ago by avibootz
0 votes
// ==================================================
// Title: Function Object with Configuration
// ==================================================
//
// A function object can expose configuration
// information and behavior together.
//
// This style is often used in libraries.
//

interface Logger {
    (message: string): void;
    level: string;
}

const logger = ((message: string): void => {
    console.log(`[${logger.level}] ${message}`);
}) as Logger;

logger.level = "INFO";

logger("Application started");

logger.level = "DEBUG";

logger("Loading configuration");



/*
run:

[INFO] Application started
[DEBUG] Loading configuration

*/

 



answered 5 days ago by avibootz

Related questions

1 answer 230 views
1 answer 203 views
1 answer 235 views
2 answers 320 views
...