Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

TypeScript: Return the typing of the input object

Let's say I have a function that receives a callback and it will return the object returned by the callback, Is there any ways that I can achieve something like this ?

const my_object = my_function<A extends string, B extends boolean>
  ("my_object", true, () => ({
    helloWorld: () => {},
    greet: () => {},
    // etc...
  }));

So that I can call it like

my_object.helloWorld();
my_object.greet();

What I did now is just something like this

const my_function = <A extends string, B extends boolean>(Name: A, other:B, callback: () => Record<string, Function>) => {
  // some code for A
  // some code for B
  // then
  return callback();
}

Above code is okay to use, but I want something more strict, because in the case

// @ts-expect-error
my_object.func_not_exist() // TypeScript do not blame on these runtime error.

And I don't want to declare the type by myself, which is something like

I don't want to do the following...

const my_function = <T>(callback: () => T): T => {
  return callback();
}

const my_object = my_function<"MyObject", true, { helloWorld: () => void; greet: () => void }>("MyObject", true, () => ({
 helloWorld: () => {},
  greet: () => {},
}))

p.s. the first two params is always required, should not and cannot remove, in this case, is it possible to do the infer stuff ?

In the real case, A is an interface extending an object, and B is the key of A, so for type-safe, they are required.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Not sure I understand your question exactly, but wouldn't this work?

function my_function<T>(callback: () => T) {
  return callback();
}

const my_object = my_function(() => ({
  helloWorld: () => {},
  greet: () => {},
  // etc...
}));

You don't need to explicitly define the types of helloWorld, greet etc. twice because they are automatically inferred by TypeScript based purely on invoking my_function with an explicitly shaped callback function...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...