diff --git a/crates/backend/src/typegen/fn.rs b/crates/backend/src/typegen/fn.rs index 08caaa29..2d6a0ae3 100644 --- a/crates/backend/src/typegen/fn.rs +++ b/crates/backend/src/typegen/fn.rs @@ -74,7 +74,7 @@ impl NapiFn { Some(_) => "", None => "static", }, - crate::FnKind::Constructor => "constructor", + crate::FnKind::Constructor => "", crate::FnKind::Getter => "get", crate::FnKind::Setter => "set", } diff --git a/crates/macro/src/parser/mod.rs b/crates/macro/src/parser/mod.rs index 0326ac55..13a1ae8f 100644 --- a/crates/macro/src/parser/mod.rs +++ b/crates/macro/src/parser/mod.rs @@ -542,6 +542,8 @@ fn napi_fn_from_decl( .trim_start_matches("set_") .to_case(Case::Camel) } + } else if opts.constructor().is_some() { + "constructor".to_owned() } else { opts.js_name().map_or_else( || ident.to_string().to_case(Case::Camel), diff --git a/examples/napi/__test__/typegen.spec.ts.md b/examples/napi/__test__/typegen.spec.ts.md index ae4d3aaf..9584e886 100644 --- a/examples/napi/__test__/typegen.spec.ts.md +++ b/examples/napi/__test__/typegen.spec.ts.md @@ -28,9 +28,9 @@ Generated by [AVA](https://avajs.dev). export function concatLatin1(s: Latin1String): string␊ export class Animal {␊ readonly kind: Kind␊ - name: string␊ constructor(kind: Kind, name: string)␊ - static new(kind: Kind, name: string): Animal␊ + get name(): string␊ + set name(name: string)␊ whoami(): string␊ }␊ ` diff --git a/examples/napi/__test__/typegen.spec.ts.snap b/examples/napi/__test__/typegen.spec.ts.snap index 39980d0c..55643bb7 100644 Binary files a/examples/napi/__test__/typegen.spec.ts.snap and b/examples/napi/__test__/typegen.spec.ts.snap differ diff --git a/examples/napi/index.d.ts b/examples/napi/index.d.ts index 7cbb680f..79530ac3 100644 --- a/examples/napi/index.d.ts +++ b/examples/napi/index.d.ts @@ -18,8 +18,8 @@ export function concatUtf16(s: Utf16String): Utf16String export function concatLatin1(s: Latin1String): string export class Animal { readonly kind: Kind - name: string constructor(kind: Kind, name: string) - static new(kind: Kind, name: string): Animal + get name(): string + set name(name: string) whoami(): string } diff --git a/examples/napi/src/class.rs b/examples/napi/src/class.rs index bfd7bff3..a6146b63 100644 --- a/examples/napi/src/class.rs +++ b/examples/napi/src/class.rs @@ -2,20 +2,33 @@ use napi::bindgen_prelude::*; use crate::r#enum::Kind; -#[napi(constructor)] +/// `constructor` option for `struct` requires all fields to be public, +/// otherwise tag impl fn as constructor +/// #[napi(constructor)] +#[napi] pub struct Animal { #[napi(readonly)] pub kind: Kind, - pub name: String, + name: String, } #[napi] impl Animal { - #[napi] + #[napi(constructor)] pub fn new(kind: Kind, name: String) -> Self { Animal { kind, name } } + #[napi(getter)] + pub fn get_name(&self) -> &str { + self.name.as_str() + } + + #[napi(setter)] + pub fn set_name(&mut self, name: String) { + self.name = name; + } + #[napi] pub fn whoami(&self) -> String { match self.kind {