-2

here is my typescript code

async function  get_string(){
  return "hellow"
}
var the_string=get_string()

in the code, the type of the_string is Promise<string> I want to somehow to remove the Promise from the type of the_string so its type is just string. maybe using the generics feature of typescript

edit: I have a good use case for this, I am working on a JavaScript interpreter that automatically resolves promises

yigal
  • 3,923
  • 8
  • 37
  • 59
  • 1
    I think you're looking for the [`Awaited`](https://www.typescriptlang.org/docs/handbook/utility-types.html#awaitedtype) utility (e.g. [`Awaited>`](https://tsplay.dev/WYK7xN) evaluates to `string` in the type system) – jsejcksn Sep 02 '23 at 05:32
  • 1
    You don't have any promise on the `get_string()` function. Show us your actual code, so we can understand it better. – Musab Sep 02 '23 at 05:33
  • 1
    Does this answer your question? [How to unwrap the type of a Promise?](https://stackoverflow.com/questions/48011353/how-to-unwrap-the-type-of-a-promise) – jsejcksn Sep 02 '23 at 05:33
  • that might work, can i do this by changing just line 4? – yigal Sep 02 '23 at 05:39
  • What do you mean by "*a JavaScript interpreter that automatically resolves promises*"? Do you mean that it uses `await` on every single expression? – Bergi Sep 02 '23 at 05:51
  • yes, but only to the statements that returned a promise @Bergi – yigal Sep 02 '23 at 05:55
  • @yigal but `get_string()` is not a statement, it's an expression? – Bergi Sep 02 '23 at 06:48
  • more specifically, for the right hand side of assignment statements – yigal Sep 02 '23 at 07:22
  • 1
    I think [that's a bad idea](https://stackoverflow.com/a/25447289/1048572), asynchronous code should be explicit. But either way, if you are building your own language (as close as it may be to JavaScript/TypeScript), you cannot easily use the TypeScript compiler on it. – Bergi Sep 02 '23 at 22:06

1 Answers1

1

If you want make an interpreter that threats promises as sync values, if may be better to get rid of promises alltogether

The primary source of promises is library async functions
Most of them have sync alternatives - like fsPromises.readFile vs readFileSync
For those without one, you may implement them yourself, as long as you have an internal function to await Promises:

Object.defineProperty(Promise.prototype, 'await', {
  get(this: Promise<any>) {
    return <intrisic await>(this)
  }
})
function fetchSync(...args: Parameters<typeof Fetch>): Awaited<ReturnType<typeof fetch>> {
   return fetch(...args).await
}
Dimava
  • 7,654
  • 1
  • 9
  • 24