Skip to content

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

Merged
armaniferrante merged 3 commits into
otter-sec:masterfrom
eoin-betdex:bugfix/fill-some-ts-type-gaps
Feb 4, 2022
Merged

Fill some gaps in generating types for Typescript from the IDL#1393
armaniferrante merged 3 commits into
otter-sec:masterfrom
eoin-betdex:bugfix/fill-some-ts-type-gaps

Conversation

@eoin-betdex

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

Copy link
Copy Markdown
Contributor

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 otter-sec:master Feb 4, 2022
@eoin-betdex

Copy link
Copy Markdown
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
Otter-0x4ka5h pushed a commit to Otter-0x4ka5h/anchor that referenced this pull request Mar 25, 2026
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