Implement Joi in Typescript

Sathya Narayanan GVK picture Sathya Narayanan GVK · Oct 16, 2019 · Viewed 10.4k times · Source

Simple joi validation snippet in javascript.It will simply return an error object when validation fails.

validate.js

const Joi =require("joi");

function validateObject (input) {
const schema = {
    key: Joi.string().required(),
  };
  return Joi.validate(input, schema);
};

let {error} = validateObject({key:5})
console.log(error)

Now I am learning typescript and like to do the exact functionality in TS.I am aware that Joi is a javascript library but can we make use of it in Typescript.When exploring I came across some alternatives like https://github.com/joiful-ts/joiful.

I am curious to know if there is any straightforward approach using Joi directly in typescript. Or little bit of changes to make the Joi work exactly like in Javascript.

WHAT I TRIED

validate.ts

import * as Joi from "joi";

export const validateObject = (input: object) => {
const schema = {
    home: Joi.string().required(),
  };
  return Joi.validate(input, schema);
};
validateObject({key:5})

While compiling, I got the error

Cannot find name 'Iterable'.

703 map(iterable: Iterable<[string | number | boolean | symbol, symbol]> | { [key: string]: symbol }): this;

UPDATE
I have installed @types/joi as suggested in the answer but still the same error

I am basically looking for validating string,boolean,number,array and object keys as it can be done easily with Joi in Javascript

Answer

Zakthedev picture Zakthedev · Oct 3, 2020

Please change const Joi =require("joi"); to import Joi from "joi"; and make sure you've installed the types by using npm install @types/joi --save-dev