Skip to content

Amplify Gen2 Types

1

Hi, I am working on a React, Tauri desktop app with Amplify Gen2 Serverless, i've bootstrapped the amplify project using npm create amplify@latest. I've followed the docs on how to define schema and carry on CRUD operations using the frontend client. The problem I'm facing is related to TypeScript types. When trying to create an entry based on a model, it doesn't show me the required input fields needed to create the entry, and I'm not sure where the types it's expecting are coming from.

Here's a snippet from my amplify/data/resource.ts:

const schema = a
  .schema({
    User: a.model({
      // id: a.id().required(),
      email: a.email().required(),
      password: a.string().required(),
      cognitoId: a.string().required(),
      userPlan: a.enum(["FREE", "PAID"]),
    }),

    Test: a.model({
      title: a.string(),
    }),
  })
  .authorization((allow) => [allow.owner()]);

Here's the code snippet that I use to create a User entry. (It works, and the entry is created, however it's complaining about type mismatch):

  const handleRegisterUser = async () => {
    try {
      const res = await client.models.User.create({
        email: "exampleATexample.com",
        password: "testpassword",
        cognitoId: "3123123123",
        userPlan: "FREE",
      });
      console.log("Creating user result: ", res);
    } catch (err) {
      console.error("Error registering user: ", err);
    }
  };

This code snippet works, but the problem is it's complaining about all the fields (email, pass, cog, userPlan):

Type 'string' is not assignable to type 'string[]'.ts(2322)
util.d.ts(15, 130): The expected type comes from property 'email' which is declared here on type '{ [x: string]: string[]; [x: number]: string[]; id?: string; }'
(method) create<never[]>(model: {
    [x: string]: string[];
    [x: number]: string[];
    id?: string;
}, options?: {
    selectionSet?: never[];
    authMode?: AuthMode;
    authToken?: string;
    headers?: CustomHeaders;
}): SingularReturnValue<{
    [x: string]: string[];
    email: string;
    password: string;
    cognitoId: string;
    userPlan: "FREE" | "PAID";
    readonly id: string;
    readonly createdAt: string;
    readonly updatedAt: string;
}>

When I tried pasing the email in an array it stops complaining about the type mismatch, but the query fails.

I'd appreciate any help.

asked a year ago219 views

3 Answers
0
Accepted Answer

After a couple of steps I think I figured out the issue. Here's what I did:

  1. Create a clean TEST app in next.js -> TypeScript autocompletion works out of the box.
  2. Compared settings from the new TEST and the current tauri app. The only mismatch i found was in tsconfig.json, in compilerOptions : { property strict = true }. So I added this to my tauri project.
  3. Rm -rf amplify/.build amplify/.temp (NOT sure if this was needed at all because I didnt see those folders when inspecting amplify folder manually).

After those I managed to fix the autocompletion problem with TypeScript.

answered a year ago

EXPERT

reviewed a year ago

0

Hi there,

When beginning with Amplify Gen 2, many developers run into this classic TypeScript configuration problem. The way the TypeScript types are generated and referenced in your project is the issue, not your data model or logic.

TypeScript is using a generic, incorrect type (one that expects array values like string[]) in place of the strongly-typed definitions produced by your resource, as indicated by the error Type'string' is not assignable to type'string[]'. Its schema.

The detailed solution is as follows:

First, create the TypeScript types. TypeScript types are automatically generated by Amplify Gen 2 using your schema; however, the code generation command must be executed. Run the following in the root of your project:

npx ampx generate types --lang typescript

Alternatively, if you are utilizing the Amplify CLI directly: amplify generate types

This command generates the type definitions, usually in./amplify/data/resource.d.ts, after reading your amplify/data/resource.ts file.

Step 2: Set Up Your tsconfig.json Your TypeScript project must contain the generated types. Make sure the files produced by Amplify are included in your tsconfig.json file.

Include or confirm this in your tsconfig.json file:

{
  "compilerOptions": {
    // ... your other options
  },
  "include": [
    "src",
    "amplify/**/*.ts" // This is the crucial line
  ]
}

Step 3: Make Use of the Properly Typed Client Using the typed client that Amplify generates is the most dependable method of obtaining complete type safety. Import and use the typed client instead of the default one.

Verify the import path in your generated./amplify/data/resource.d.ts file first. Usually, you will find an export such as Client. Next, incorporate it into your component: typescript

// Import the typed client. The exact path might vary.
import { client } from "./amplify/data/resource"; // or from '../amplify/data/resource'

// Your function with proper typing
const handleRegisterUser = async () => {
  try {
    // Now, when you type `client.models.User.create({`
    // TypeScript should provide full intellisense for the fields
    const { data: user, errors } = await client.models.User.create({
      email: "example@example.com", // Should be a string, not string[]
      password: "testpassword",
      cognitoId: "3123123123",
      userPlan: "FREE", // This should now be correctly typed as "FREE" | "PAID" | undefined
    });

    if (errors) {
      console.error("Errors creating user:", errors);
      return;
    }

    console.log("Successfully created user:", user);
    // `user` is now strongly typed with id, createdAt, updatedAt, etc.
  } catch (err) {
    console.error("Unexpected error registering user:", err);
  }
};

Important Points to Confirm: Absence of an ID field id: a.id().required() has been commented out. Your method is correct because Amplify Gen 2 adds the id field for you automatically if you don't define one. id: string, createdAt: string, and updatedAt: string will all be automatically included in the generated type.

Required vs. Optional: Since your email address, password, and cognitoId are defined as.required(), they must be entered in the create input. Since the userPlan is optional, its type should be "FREE" | "PAID" | undefined.

Restart Your IDE/Language Server: Restart your TypeScript language server following type generation and configuration modifications. You can accomplish this in VSCode by launching "TypeScript: Restart TS Server" in the command palette (Ctrl+Shift+P). This crucial step frequently fixes persistent type issues. If the issue continues There may be a configuration conflict if, even after following these steps, you continue to see the incorrect types.

Verify if you are not inadvertently importing a generic client from another package (such as aws-amplify/api) by checking for multiple clients. The client created especially for your Gen 2 backend is what you should be using.

Examine the Generated File: Locate the User type by opening./amplify/data/resource.d.ts. The create input should have a precise definition that aligns with your schema.

In conclusion, the answer is to make sure that your TypeScript project is set up to include the Amplify types (npx ampx generate types) and that they are generated. After completing this, you will receive full IntelliSense and type checking, which will remove the string[] error and display the precise fields that are needed. Kindly follow these instructions and inform us if the type problems have been fixed.

answered a year ago

EXPERT

reviewed a year ago

0

Hi, Thank you for you reply.

Following the steps you described, I cannot get too far since the npx generate types --lang typescript does not exist, the only available generate commands are:

 ampx generate outputs               Generates Amplify backend outputs
  ampx generate forms                 Generates UI forms
  ampx generate graphql-client-code   Generates graphql API code (creates API.ts, queries, mutations, subscriptions.ts)
  ampx generate schema-from-database Generates typescript data schema from a SQL database

Also, amplify did not generate any standalone typed client instance in my amplify/data/resource.ts. The only file my amplify generates after npx ampx sandbox is the amplify_outputs.json in root, that has the correct types of my models:

"model_introspection": {
      "version": 1,
      "models": {
        "User": {
          "name": "User",
          "fields": {
            "id": {
              "name": "id",
              "isArray": false,
              "type": "ID",
              "isRequired": true,
              "attributes": []
            },
            "email": {
              "name": "email",
              "isArray": false,
              "type": "String",
              "isRequired": true,
              "attributes": []
            },
            "password": {
              "name": "password",
              "isArray": false,
              "type": "String",
              "isRequired": true,
              "attributes": []
            },
            "cognitoId": {
              "name": "cognitoId",
              "isArray": false,
              "type": "String",
              "isRequired": true,
              "attributes": []
            },
            "userPlan": {
              "name": "userPlan",
              "isArray": false,
              "type": {
                "enum": "UserUserPlan"
              },
              "isRequired": false,
              "attributes": []
            },

answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.