Writing code

CLASS

FunctionParameter

@skmtc/lang-typescript 0.19.1

Generates TypeScript function parameters with advanced handling for different parameter patterns.

FunctionParameter is a sophisticated utility for generating TypeScript function parameter syntax that handles multiple parameter patterns including named parameters, destructured object parameters, and void parameters. It provides intelligent type handling and can generate both the parameter declaration and the parameter usage patterns.

This class is essential for generating type-safe function signatures in API clients, utility functions, and other generated code where parameters need to be handled consistently and safely.

Supported Parameter Patterns

  • Named Parameters: Traditional paramName: Type syntax
  • Destructured Parameters: { prop1, prop2 }: ObjectType syntax
  • Void Parameters: No parameters when dealing with void types
  • Optional Parameters: Automatic handling of optional parameter markers
  • Empty Filtering: Option to skip empty properties in destructured objects

Signature

import { FunctionParameter } from '@skmtc/lang-typescript'

class FunctionParameter

Examples

Named parameter generation
import { FunctionParameter, createVariable } from '@skmtc/lang-typescript';

const userIdParam = new FunctionParameter({
  name: 'userId',
  typeDefinition: new Definition({
    context: generateContext,
    identifier: createType('string'),
    value: { type: 'string' }
  }),
  required: true
});

console.log(userIdParam.toString()); // 'userId: string'
console.log(userIdParam.toInbound()); // 'userId'
Destructured parameter generation
const destructuredParam = new FunctionParameter({
  typeDefinition: new Definition({
    context: generateContext,
    identifier: createType('UserParams'),
    value: {
      type: 'object',
      objectProperties: {
        properties: {
          name: { type: 'string' },
          email: { type: 'string' },
          age: { type: 'number' }
        }
      }
    }
  }),
  destructure: true,
  required: true
});

console.log(destructuredParam.toString());
// '{ name, email, age }: UserParams'

console.log(destructuredParam.toInbound());
// '{ name, email, age }'
Optional parameter handling
const optionalParam = new FunctionParameter({
  name: 'options',
  typeDefinition: optionsTypeDefinition,
  required: false
});

console.log(optionalParam.toString()); // 'options?: OptionsType'
Void parameter handling
const voidParam = new FunctionParameter({
  typeDefinition: new Definition({
    context: generateContext,
    identifier: createType('void'),
    value: { type: 'void' }
  })
});

console.log(voidParam.toString()); // ''
console.log(voidParam.toInbound()); // ''
Property checking
const objectParam = new FunctionParameter({
  typeDefinition: userTypeDefinition,
  destructure: true,
  required: true
});

if (objectParam.hasProperty('email')) {
  // Handle email property access
  console.log('Parameter includes email property');
}

const propertyList = objectParam.toPropertyList();
console.log(propertyList.toString()); // '{name, email, age}'
API method generation with parameters
class ApiMethodGenerator {
  generateMethod(
    methodName: string,
    pathParams?: FunctionParameter,
    bodyParam?: FunctionParameter
  ) {
    const parameters = [pathParams, bodyParam]
      .filter(p => p && p.toString())
      .map(p => p!.toString())
      .join(', ');

    const pathInbound = pathParams?.toInbound() || '';
    const bodyInbound = bodyParam?.toInbound() || '';

    return `
async ${methodName}(${parameters}) {
  const path = this.buildPath(${pathInbound});
  return this.request('POST', path, ${bodyInbound});
}`;
  }
}
Empty property filtering
const filteredParam = new FunctionParameter({
  typeDefinition: sparseObjectDefinition,
  destructure: true,
  required: true,
  skipEmpty: true // Skip properties with empty types
});

// Only non-empty properties will be included in destructuring
console.log(filteredParam.toString());
// '{ validProp1, validProp2 }: FilteredType' (empty props omitted)

Constructor

constructor

constructor(args: FunctionParameterArgs)

Creates a new FunctionParameter instance with the specified configuration.

The constructor analyzes the provided type definition and configuration options to determine the appropriate parameter pattern (void, regular, or destructured). It handles the complex logic of parameter type determination and validation.

args

Configuration options for the function parameter

Throws
Error

When the parameter configuration is invalid

Properties

properties, ParameterProperties

The internal parameter configuration determining how the parameter is generated

skipEmpty, boolean | undefined

Whether to skip empty properties in destructured parameters

Methods

hasProperty

hasProperty(name: string): boolean

Checks if the parameter has a specific property (for object-based parameters).

This method determines whether a given property name exists within the parameter's type structure. It's useful for conditional code generation based on available properties and only returns true for object-based parameters (regular object parameters or destructured parameters).

name

The property name to check for

Returns

True if the property exists in the parameter's type structure

toPropertyList

toPropertyList(): List

Generates a List of the variables that the parameter declares.

For a regular parameter the list has the parameter name. For a destructured parameter it has the variable of each property, as toParameterVariable names it. For a void parameter it is empty.

Read the variables from values. toString() of a destructured list keeps its braces and has no renames; for the object use toInbound.

Returns

List containing the parameter's variables

toInbound

toInbound(): string

Generates the inbound parameter syntax for function calls.

This method produces the syntax used when calling a function with this parameter. For regular parameters, it returns the parameter name. For destructured parameters, it returns the destructured object syntax. For void parameters, it returns an empty string.

Returns

The inbound parameter syntax string

toString

toString(): string

Generates the complete function parameter declaration syntax.

This method produces the full parameter declaration that appears in a function signature, including the parameter name, type annotation, and optional markers. It handles all parameter patterns supported by the class.

Returns

The complete parameter declaration string