fix(napi-derive): async task optional output type (#1796)

This commit is contained in:
LongYinan 2023-11-08 20:06:27 +08:00 committed by GitHub
parent 938f4df83d
commit e930a6aab3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 32 additions and 2 deletions

View file

@ -263,6 +263,7 @@ fn is_ts_function_type_notation(ty: &Type) -> bool {
} }
} }
// return (type, is_optional, is_variadic)
pub fn ty_to_ts_type( pub fn ty_to_ts_type(
ty: &Type, ty: &Type,
is_return_ty: bool, is_return_ty: bool,

View file

@ -36,13 +36,17 @@ impl ToTypeDef for NapiImpl {
fn to_type_def(&self) -> Option<TypeDef> { fn to_type_def(&self) -> Option<TypeDef> {
if let Some(output_type) = &self.task_output_type { if let Some(output_type) = &self.task_output_type {
TASK_STRUCTS.with(|t| { TASK_STRUCTS.with(|t| {
let resolved_type = ty_to_ts_type(output_type, false, true, false).0; let (resolved_type, is_optional, _) = ty_to_ts_type(output_type, false, true, false);
t.borrow_mut().insert( t.borrow_mut().insert(
self.name.to_string(), self.name.to_string(),
if resolved_type == "undefined" { if resolved_type == "undefined" {
"void".to_owned() "void".to_owned()
} else {
if is_optional {
format!("{} | null", resolved_type)
} else { } else {
resolved_type resolved_type
}
}, },
); );
}); });

View file

@ -246,6 +246,8 @@ Generated by [AVA](https://avajs.dev).
export function asyncReduceBuffer(buf: Buffer): Promise<number> export function asyncReduceBuffer(buf: Buffer): Promise<number>
export function asyncTaskOptionalReturn(): Promise<number | null>
export function asyncTaskVoidReturn(): Promise<void> export function asyncTaskVoidReturn(): Promise<void>
export interface B {␊ export interface B {␊

View file

@ -236,6 +236,8 @@ export function asyncPlus100(p: Promise<number>): Promise<number>
export function asyncReduceBuffer(buf: Buffer): Promise<number> export function asyncReduceBuffer(buf: Buffer): Promise<number>
export function asyncTaskOptionalReturn(): Promise<number | null>
export function asyncTaskVoidReturn(): Promise<void> export function asyncTaskVoidReturn(): Promise<void>
export interface B { export interface B {

View file

@ -49,3 +49,24 @@ impl Task for AsyncTaskVoidReturn {
fn async_task_void_return() -> AsyncTask<AsyncTaskVoidReturn> { fn async_task_void_return() -> AsyncTask<AsyncTaskVoidReturn> {
AsyncTask::new(AsyncTaskVoidReturn {}) AsyncTask::new(AsyncTaskVoidReturn {})
} }
struct AsyncTaskOptionalReturn {}
#[napi]
impl Task for AsyncTaskOptionalReturn {
type JsValue = Option<u32>;
type Output = ();
fn compute(&mut self) -> Result<Self::Output> {
Ok(())
}
fn resolve(&mut self, _env: Env, _: Self::Output) -> Result<Self::JsValue> {
Ok(None)
}
}
#[napi]
fn async_task_optional_return() -> AsyncTask<AsyncTaskOptionalReturn> {
AsyncTask::new(AsyncTaskOptionalReturn {})
}