4

I know what the type 'void' do on typescript.But i faced following code.

function (obj: void){}

I saw same on typescript documentation https://www.typescriptlang.org/docs/handbook/functions.html

What does type "void" as parameter of funсtion?

1

2 Answers 2

4

void is useful as a this type, as it promises that you won't use the this parameter.

function f(this: void, ...) {
  // Can't use `this` in here.
}

On other parameters, it's... not as useful. If you have --strictNullChecks off, then you can still call the function by passing null or undefined as the void parameter. If you don't, then you can't even call the function, as void is uninhabited.

If you haven't seen this written as a function parameter before, I suggest you read this section (pun entirely intended) of the documentation.

Sign up to request clarification or add additional context in comments.

1 Comment

you can still call a (a: void) => void with no parameter or with any
0

In short, void is used to denote lack of value. You can think of it as another way to say undefined.

const foo: void = undefined;

When used as the return type, void communicates that the function will not explicitly return anything.

function log(argument: any): void {
  console.log(argument);
}

Although in runtime log implicitly does return undefined, TypeScript makes the conceptual distinction between void and undefined.

function log(argument: any): void {
    console.log(argument);
}

const foo: undefined = log('Hello'); // Error — "void" is not "undefined"

When used as the this type, void communicates that the this used during a function call will be the default context of execution — the global scope. There are a few cases where it helps. Creating scope-safe constructors is one of them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.