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

Fill some gaps in generating types for Typescript from the IDL #1393

Merged
merged 3 commits into from
Feb 4, 2022
Merged

Fill some gaps in generating types for Typescript from the IDL #1393

merged 3 commits into from
Feb 4, 2022

Conversation

eoin-betdex
Copy link
Contributor

@eoin-betdex eoin-betdex commented Feb 4, 2022

Closes #1392

We've run up against two small issues when working in Typescript with the types generated for account fields from the IDLs.

  1. Option<T> fields map to unknown type in Typescript when T is one of the standard types defined in TypeMap, e.g.,
#[account]
pub struct MyAccount {
    pub counter: Option<u16>,
}
const accountAddress = "...";
const myAccount = await myProgram.account.myAccount.fetch(accountAddress);
const counterPlusOne = myAccount.counter + 1;  // Assuming the counter has been initialised

Results in TS2365: Operator '+' cannot be applied to types 'unknown' and '1'.

Adding in an additional clause to DecodeType<T extends IdlType, Defined> allows the types declared in TypeMap to be supported as type parameters of Option<T>, and for those types to map correctly into Typescript types.

  1. Vec<String> fields map to unknown type in Typescript. Only the types defined in TypeMap are considered when determining how to map a Vec<T> to some T'[].
#[account]
pub struct MyAccount {
    pub my_strings: Vec<String>,
}
const accountAddress = "...";
const myAccount = await myProgram.account.myAccount.fetch(accountAddress);
const myStrings = myAccount.myStrings;

for (const myString of myStrings) { ...

Results in TS2488: Type 'unknown' must have a '[Symbol.iterator]()' method that returns an iterator. Adding in a mapping from string: string in TypeMap corrects this.

Keen for input on whether we can get this fixed and if there are any additional changes we should make or code paths we should investigate; Or to understand if there are other changes to type support in Typescript coming that means we should leave this as it is for now.

Thanks!

@armaniferrante armaniferrante merged commit 9fea72e into coral-xyz:master Feb 4, 2022
@eoin-betdex
Copy link
Contributor Author

Thanks!

@eoin-betdex eoin-betdex deleted the bugfix/fill-some-ts-type-gaps branch February 7, 2022 09:18
losman0s pushed a commit to losman0s/anchor that referenced this pull request Feb 7, 2022
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.

Gaps in generated types for Typescript (Option and Vec<String>)
2 participants