How to Set Inline Default Value For Function Args When Using TypeScript?

You can specify default value inline for a function argument by adding the default value after the type declaration, for example, like so:

function (obj: MyCustomObject = {}) {
    // ...
}

For most values, however, TypeScript can automatically infer the type of the argument from the default value you specify. Therefore, explicit type declaration might be needed, such as in the following case:

function (counter = 1) {
    // ...
}

You could also use generics to help TypeScript infer types. This is especially useful for building flexible and reusable functions. For example:

function toNumber<Input>(arr: Input[] = []): number[] {
    return arr.map((num) => Number.parseInt(String(num)));
}

const parsed = toNumber(['1', '2', '3', 'foo']);

console.log(parsed); // [1, 2, 3, NaN]

Based on the usage in "parsed", TypeScript will infer it as:

// function toNumber<string>(arr?: string[]): number[]
const parsed = toNumber(['1', '2', '3', 'test']);

Hope you found this post useful. It was published . Please show your love and support by sharing this post.