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

fix: generate BigInt type as bigint #151

Merged
merged 1 commit into from Oct 3, 2023

Conversation

avinassh
Copy link
Contributor

@avinassh avinassh commented Oct 3, 2023

The type of BigInt in Typescript is bigint (not BigInt). bigint is the type and BigInt is the constructor.

Here is the typescript docs for reference: https://typescriptlang.org/docs/handbook/release-notes/typescript-3-2.html#bigint

BigInt support in TypeScript introduces a new primitive type called the bigint (all lowercase). You can get a bigint by calling the BigInt() function or by writing out a BigInt literal by adding an n to the end of any integer numeric literal

let foo: bigint = BigInt(100); // the BigInt function
let bar: bigint = 100n; // a BigInt literal

function fibonacci(n: bigint) {
...
}

I need this to stop VSCode to complain :)

@oscartbeaumont
Copy link
Owner

Good catch although be careful using bigint types due to the loss of precision that can happen with JSON.parse!

@oscartbeaumont oscartbeaumont merged commit 8eeec58 into oscartbeaumont:main Oct 3, 2023
4 checks passed
@avinassh avinassh deleted the bigint branch October 3, 2023 12:53
@avinassh
Copy link
Contributor Author

avinassh commented Oct 3, 2023

@oscartbeaumont thank you for the quick merge!

you are right, I did run into the bug. What is the right way to handle bigint types? (I am using specta with tauri-specta)

@oscartbeaumont
Copy link
Owner

Your best bet is to convert it to a string using Serde and manually decode it to a BigInt on the frontend. It's annoying but the issue is with JSON.parse so nothing Specta can do about it.

You can do it like so:

#[derive(Serialize, Type)]
struct Header {
	#[specta(type = String)]
	#[serde(serialize_with = "as_string")]
	timestamp: u128,
}

fn as_string<T: ToString, S>(x: &T, s: S) -> Result<S::Ok, S::Error>
where
	S: Serializer,
{
	s.serialize_str(&x.to_string())
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants