Oops! Looks like Deno encountered an error (TS2339) because it couldn't find the property x

Exploring Oak and Deno for the first time has been an exciting journey. I came across a helpful guide at along with the official documentation. My aim is to use REST-API deno by utilizing the script provided in (server.ts).

import { v4 } from 'https://deno.land/std/uuid/mod.ts';

import {
  Application,
  Router,
  helpers,
} from 'https://deno.land/x/oak/mod.ts';

interface User {
  id: string;
  username: string;
}

const users = new Map<string, User>();

users.set('1', {
  id: '1',
  username: 'Robin Wieruch',
});

users.set('2', {
  id: '2',
  username: 'Dave Davids',
});

interface Message {
  id: string;
  text: string;
  userId: string;
}

const messages = new Map<string, Message>();

messages.set('1', {
  id: '1',
  text: 'Hello World',
  userId: '1',
});

messages.set('2', {
  id: '2',
  text: 'By World',
  userId: '2',
});

const port = 8000;
const app = new Application();

const router = new Router();

router.get('/session', (ctx) => {
  ctx.response.body = users.get(ctx.state.me.id);
});

router.get('/users', (ctx) => {
  ctx.response.body = Array.from(users.values());
});

router.get('/users/:userId', (ctx) => {
  const { userId } = helpers.getQuery(ctx, { mergeParams: true });
  ctx.response.body = users.get(userId);
});

router.get('/messages', (ctx) => {
  ctx.response.body = Array.from(messages.values());
});

router.get('/messages/:messageId', (ctx) => {
  const { messageId } = helpers.getQuery(ctx, { mergeParams: true });
  ctx.response.body = messages.get(messageId);
});

router.post('/messages', async (ctx) => {
  const id = v4.generate();

  const {
    value: { text },
  } = await ctx.request.body();

  messages.set(id, {
    id,
    text,
    userId: ctx.state.me.id,
  });

  ctx.response.body = messages.get(id);
});

router.delete('/messages/:messageId', async (ctx) => {
  const { messageId } = helpers.getQuery(ctx, { mergeParams: true });

  const isDeleted = messages.delete(messageId);

  ctx.response.body = isDeleted;
});

app.use(async (ctx, next) => {
  ctx.state = { me: users.get('1') };

  await next();
});

app.use(router.allowedMethods());
app.use(router.routes());

app.addEventListener('listen', () => {
  console.log(`Listening on: localhost:${port}`);
});

await app.listen({ port });

Upon executing it using

deno run --allow-net --allow-read server.ts
, I encountered the following error:

$ deno run --allow-net --allow-read server.ts 
Check file:///home/astrid/git/javascript/deno/deno-oak-rest-api/server.ts
error: TS2339 [ERROR]: Property 'text' does not exist on type 'Promise<any> | Promise<URLSearchParams> | FormDataReader | Promise<string> | Promise<Uint8Array> | undefined'.
    value: { text },
             ~~~~
    at file:///home/astrid/git/javascript/deno/deno-oak-rest-api/server.ts:77:14

My current version details are as follows:

$ deno --version
deno 1.3.3
v8 8.6.334
typescript 4.0.2

I am seeking advice on how to resolve this error. Any insights would be greatly appreciated!

Answer №1

Changes were made starting at #201

  • ctx.request.body() is now synchronous, no need for await
  • You can now specify the type of body as an argument
  • value is now a promise and needs to be awaited (as indicated by the ts issue)

If you are unsure about the body type you were using before, here are some examples in the latest version:

// for JSON:
const { value } = ctx.request.body({ type: "json" });
const { text } = await value;

// for FormData:
const { value } = ctx.request.body({ type: "form-data" });
const formData = await value.read();
const { text } = formData.fields;

Visit https://github.com/oakserver/oak/issues/239 for more information

Answer №2

Important: Extracting parsed information from a JSON request can be done as follows:

const jsonData = context.request.body({ type: "json" });
const extractedData = await jsonData.value;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Typescript is experiencing an error due to the use of attr("disabled", false) causing a disruption

Within my ts file, I'm using the code snippet below: $('input[type=hidden]').attr("disabled", false); The code functions as intended, however, an error persists: Argument of type 'false' is not assignable to parameter of typ ...

Achieving VS Code/typescript autocomplete functionality without the need to import the library

When a module (for example, moment.js, knockout, or big.js) is added with a <script> tag like this: <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"> </script> that defines a global property (for instance ...

How can we avoid excessive re-rendering of a child component in React when making changes to the parent's state?

In my React application, I am facing a situation where a parent component controls a state variable and sends it to a child component. The child component utilizes this state in its useEffect hook and at times modifies the parent's state. As a result, ...

The process of implementing ngOninit with asynchronous data involves handling data that may take

Within the ngOnInit method, I am calling a service method and assigning the return value to a member variable. However, when trying to access this variable later in the ngOnInit again, it seems that due to synchronization issues, the value has not been ass ...

The argument provided is a string type, which cannot be assigned to a parameter expecting an object with a 'results' property of type string

When attempting to pass the result.nativeEvent.message to another function, I am encountering the error: Argument of type 'string' is not assignable to parameter of type '{ results: string; } on onUnityMessageController(result.nativeEvent.me ...

Navigate to the logout page upon encountering an error during the request

I recently upgraded our application from angular 2 to angular 5 and also made the switch from the deprecated Http module to the new HttpClient. In the previous version of the application, I used the Http-Client to redirect to a specific page in case of er ...

What are the best methods for implementing runtime type checking in JavaScript?

Utilizing either TypeScript or Facebook's Flow (type), I am empowered to statically assign types to variables like this: function add (x: integer, y: integer) { ... } Both TypeScript and Flow are able to identify and prevent incorrect invocations su ...

Using Typescript, develop a function within an entity to verify the value of a property

In my Angular 7 app, I have an entity defined in my typescript file as follows: export class FeedbackType { id: number; name: String; } I am looking to create a function within this entity that checks the value of a property. For example: feedba ...

Is the input URL modified by the Angular HttpClientModule's GET request?

I am currently using an Angular service to make calls to a Node.js server in order to fetch data. Here is a snippet of my code: constructor(private http: HttpClient){ } getPersonData(): Observable<person[]> { //return this.http.get<person ...

Mastering the Type Checking of React Select's onChange Event Handler

Currently, I am in the process of building a design system based on React TypeScript. For the Dropdown component, I have opted to utilize React Select to handle most of its functionality. To customize the Dropdown component, I have created a wrapper compo ...

Ways to selectively apply colors to particular rows within an AntD table

I'm attempting to apply different colors to entire rows depending on certain data values from the table's data source. I know that we can utilize rowClassName, but I'm not entirely clear on its functionality. If anyone could provide exampl ...

Getting a specific array from the API with fetch in Angular: A step-by-step guide

I am trying to retrieve images from an API, but I'm having trouble accessing all the arrays to get to the data. Currently, I am only able to fetch the posts arrays in a single call and not beyond that. https://i.stack.imgur.com/aFWlD.jpg My method fo ...

Angular is set up to showcase every single image that is stored within an array

I am having trouble displaying the images from the "image_url" array using a for loop. The images are not showing up as expected. Here is the content of the array: image_url: [ 0: "https://xyz/16183424594601618342458.5021539.jpg" 1: "https://xyz/1618342459 ...

Trouble arises when extending an MUI component due to a TypeScript error indicating a missing 'css' property

We have enhanced the SnackbarContent component by creating our own custom one called MySnackbarContent: export interface MySnackbarContentProps extends Omit<SnackbarContentProps, 'variant'> { variant?: MyCustomVariant; type?: MyCustomTy ...

Sequelize v5 & Typescript Model Loader

Having previous experience with Sequelize for projects (v4), I am now venturing into starting a new project using Sequelize v5 & Typescript. I have been following Sequelize's documentation on how to define Models at: https://sequelize.org/master/ ...

Dealing With HttpClient and Asynchronous Functionality in Angular

I've been pondering this issue all day. I have a button that should withdraw a student from a class, which is straightforward. However, it should also check the database for a waiting list for that class and enroll the next person if there is any. In ...

Utilizing Azure Function Model v4: Establishing a Connection with Express.js

Using Model v4 in my Azure function index.ts import { app } from "@azure/functions"; import azureFunctionHandler from "azure-aws-serverless-express"; import expressApp from "../../app"; app.http("httpTrigger1", { methods: ["GET"], route: "api/{*segme ...

Unable to locate the necessary file. - Implementing TypeScript in a React application

Attempting to integrate TypeScript into an existing React app by following the steps outlined at: https://create-react-app.dev/docs/adding-typescript I've followed all the instructions but encountered the following error upon trying to launch the app ...

"Encountering an issue where attempting to set a property on an undefined variable, despite it being

I've been working on a timer app/component, but I'm running into an issue. The error message reads: Cannot set property startAt of undefined. I've defined it in my dashboard component, so I'm not sure where the problem lies. Any suggest ...

Using an existing function with no arguments as a handler in Typescript and React: A Step-by-Step Guide

NOTE: I'm still learning Typescript, so I may be missing something obvious here. Let's consider a basic scenario in React Javascript, using a Material-UI Button: // Closing dialog event handler without needing an 'event' argument const ...