如何在 ts-node 中 运行 "TS" 代码片段?

How to run "TS" code snippets in ts-node?

在 Solana 文档中,他们使用了很多 TS 代码片段,例如下面的 link(第一个代码片段)应该 运行 和 return 一个值: https://solanacookbook.com/guides/get-program-accounts.html#filters

我尝试 运行 第一个片段使用:ts-node file.ts 但是我得到了这个错误:

    return new TSError(diagnosticText, diagnosticCodes);
           ^
TSError: ⨯ Unable to compile TypeScript:
index.ts:33:26 - error TS7053: Element implicitly has an 'any' type because expression of type '"parsed"' can't be used to index type 'Buffer | ParsedAccountData'.
  Property 'parsed' does not exist on type 'Buffer | ParsedAccountData'.

33     console.log(`Mint: ${account.account.data["parsed"]["info"]["mint"]}`);
                            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
index.ts:35:18 - error TS7053: Element implicitly has an 'any' type because expression of type '"parsed"' can't be used to index type 'Buffer | ParsedAccountData'.
  Property 'parsed' does not exist on type 'Buffer | ParsedAccountData'.

35       `Amount: ${account.account.data["parsed"]["info"]["tokenAmount"]["uiAmount"]}`
                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    at createTSError (/usr/local/lib/node_modules/ts-node/src/index.ts:750:12)
    at reportTSError (/usr/local/lib/node_modules/ts-node/src/index.ts:754:19)
    at getOutput (/usr/local/lib/node_modules/ts-node/src/index.ts:941:36)
    at Object.compile (/usr/local/lib/node_modules/ts-node/src/index.ts:1243:30)
    at Module.m._compile (/usr/local/lib/node_modules/ts-node/src/index.ts:1370:30)
    at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Object.require.extensions.<computed> [as .ts] (/usr/local/lib/node_modules/ts-node/src/index.ts:1374:12)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) {
  diagnosticText: `\x1B[96mindex.ts\x1B[0m:\x1B[93m33\x1B[0m:\x1B[93m26\x1B[0m - \x1B[91merror\x1B[0m\x1B[90m TS7053: \x1B[0mElement implicitly has an 'any' type because expression of type '"parsed"' can't be used to index type 'Buffer | ParsedAccountData'.\n` +
    "  Property 'parsed' does not exist on type 'Buffer | ParsedAccountData'.\n" +
    '\n' +
    '\x1B[7m33\x1B[0m     console.log(`Mint: ${account.account.data["parsed"]["info"]["mint"]}`);\n' +
    '\x1B[7m  \x1B[0m \x1B[91m                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\x1B[0m\n' +
    `\x1B[96mindex.ts\x1B[0m:\x1B[93m35\x1B[0m:\x1B[93m18\x1B[0m - \x1B[91merror\x1B[0m\x1B[90m TS7053: \x1B[0mElement implicitly has an 'any' type because expression of type '"parsed"' can't be used to index type 'Buffer | ParsedAccountData'.\n` +
    "  Property 'parsed' does not exist on type 'Buffer | ParsedAccountData'.\n" +
    '\n' +
    '\x1B[7m35\x1B[0m       `Amount: ${account.account.data["parsed"]["info"]["tokenAmount"]["uiAmount"]}`\n' +
    '\x1B[7m  \x1B[0m \x1B[91m                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\x1B[0m\n',
  diagnosticCodes: [ 7053, 7053 ]
}

我这样做正确吗?

据我所知,你 运行 正确。看起来与 Typescript 的兼容性代码存在一个问题。 account.account.data 属于 Buffer | ParsedAccountData.

类型

如果您像下面的代码那样设置,它将运行成功:

import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import { ParsedAccountData } from "@solana/web3.js";
import { clusterApiUrl, Connection } from "@solana/web3.js";

(async () => {
  const MY_WALLET_ADDRESS = "FriELggez2Dy3phZeHHAdpcoEXkKQVkv6tx3zDtCVP8T";
  const connection = new Connection(clusterApiUrl("devnet"), "confirmed");

  const accounts = await connection.getParsedProgramAccounts(
    TOKEN_PROGRAM_ID, // new PublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")
    {
      filters: [
        {
          dataSize: 165, // number of bytes
        },
        {
          memcmp: {
            offset: 32, // number of bytes
            bytes: MY_WALLET_ADDRESS, // base58 encoded string
          },
        },
      ],
    }
  );

  console.log(
    `Found ${accounts.length} token account(s) for wallet ${MY_WALLET_ADDRESS}: `
  );
  accounts.forEach((account, i) => {
    console.log(
      `-- Token Account Address ${i + 1}: ${account.pubkey.toString()} --`
    );
    console.log(`Mint: ${(account.account.data as ParsedAccountData)["parsed"]["info"]["mint"]}`);
    console.log(
      `Amount: ${(account.account.data as ParsedAccountData)["parsed"]["info"]["tokenAmount"]["uiAmount"]}`
    );
  });
  /*
    // Output

    Found 1 token account(s) for wallet FriELggez2Dy3phZeHHAdpcoEXkKQVkv6tx3zDtCVP8T: 
    -- Token Account Address 1: Et3bNDxe2wP1yE5ao6mMvUByQUHg8nZTndpJNvfKLdCb --
    Mint: BUGuuhPsHpk8YZrL2GctsCtXGneL1gmT5zYb7eMHZDWf
    Amount: 3
  */
})();