Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reflect optional struct fields in typescript #1990

Merged
merged 3 commits into from
Feb 18, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions crates/cli-support/src/js/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -699,8 +699,13 @@ impl<'a> Context<'a> {
ts_dst.push_str("readonly ");
}
ts_dst.push_str(name);
ts_dst.push_str(": ");
ts_dst.push_str(ty);
if &ty[0..1] == "?" {
ts_dst.push_str("?: ");
ts_dst.push_str(&ty[1..]);
} else {
ts_dst.push_str(": ");
ts_dst.push_str(&ty);
}
ts_dst.push_str(";\n");
}
dst.push_str("}\n");
Expand Down Expand Up @@ -772,9 +777,7 @@ impl<'a> Context<'a> {
if !self.should_write_global("not_defined") {
return;
}
self.global(
"function notDefined(what) { return () => { throw new Error(`${what} is not defined`); }; }"
);
self.global("function notDefined(what) { return () => { throw new Error(`${what} is not defined`); }; }");
}

fn expose_assert_num(&mut self) {
Expand Down Expand Up @@ -3067,7 +3070,13 @@ impl ExportedClass {
.typescript_fields
.entry(field.to_string())
.or_insert_with(Default::default);
*ty = ret_ty.to_string();

if docs.contains("| undefined") {
*ty = "?".to_string() + ret_ty;
} else {
*ty = ret_ty.to_string();
}
alexcrichton marked this conversation as resolved.
Show resolved Hide resolved

has_setter
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/typescript-tests/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod custom_section;
pub mod getters_setters;
pub mod opt_args_and_ret;
pub mod optional_fields;
pub mod simple_fn;
pub mod simple_struct;
7 changes: 7 additions & 0 deletions crates/typescript-tests/src/optional_fields.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub struct Fields {
pub hallo: Option<bool>,
pub spaceboy: bool,
}
3 changes: 3 additions & 0 deletions crates/typescript-tests/src/optional_fields.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import * as wbg from '../pkg/typescript_tests';

const fields: wbg.Fields = { spaceboy: true, free: () => { } };
1 change: 1 addition & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
tab_spaces = 4