M
M
maratt2019-12-20 19:05:04
typescript
maratt, 2019-12-20 19:05:04

How to replace with interface?

there is a function

function test(a: number, b: string, c: () => void): void {
  ...
}

how to use interface here?
interface TestInterface {
  a: number;
  b: string;
  c: () => void;
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Robur, 2019-12-20
@Robur

function test({a,b,c}: TestInterface)

A
Aetae, 2019-12-21
@Aetae

Use the Robur variant .
Why? Because in a general sense, what you want to automatically get is impossible, because. the order of the keys in the object (and interface) does not matter, i.e. there is no difference between:

interface TestInterface {
  a: number;
  b: string;
  c: () => void;
}
and
interface TestInterface {
  c: () => void;
  a: number;
  b: string;
}
and in function, obviously, has.
You can do it manually like this:
function test(a: TestInterface['a'], b: TestInterface['b'], c: TestInterface['c']): void {
  // ,,,
}

If the order of the arguments doesn't really matter, you can make a nightmare of a complex type in a prinip using ...args, but you don't have to.)

F
forspamonly2, 2019-12-22
@forspamonly2

the common type for all function arguments (aka rest parameter type) is tuple .
so, in your case , you need to pass it with three dots. the only thing is, if you pass the array directly as a literal, you will need to indicate that it understands that this is a tuple. here's an example of what works and what doesn't in the playground .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question