Home > Back-end >  Type 'string' is not assignable to type 'null | undefined'
Type 'string' is not assignable to type 'null | undefined'

Time:07-21

I'm adding some TS features to an existing React JS project. One of the existing JS functions has default params of null

  const existingFunction = ({ firstName = null, lastName = null }) => {}

If I try to use that function and provide strings for those parameters, I get the following error

existingFunction({ firstName: "John", lastName: "Smith" });

Error:
Type 'string' is not assignable to type 'null | undefined'.

I've tried typing the params but I keep getting the same error.

Type Name = {
  firstName?: string;
  lastName?: string;
}
const user:Name = { firstName: "John", lastName: "Smith" }
existingFunction(user)

Error:
Type 'string' is not assignable to type 'null | undefined'.

The only way I can get this working is to type the firstName and lastName properties as any types, which I'd prefer not to do

Any suggestions? Thanks!

EDIT: existingFunction is a JavaScript function so I can't add types to it.

CodePudding user response:

Your existing function needs better typing. The right call signature is like

declare const existingFunction: (
  param: { firstName?: string | null, lastName?: string | null }
) => void

Since that function is in JavaScript, you would need to do something like use JSDoc to provide type hints. Maybe:

/**
 * @typedef {Object} Param 
 * @property {string | null} [firstName]
 * @property {string | null} [lastName]
 * @param {Param} p 
 */
const existingFunction = (
    { firstName = null, lastName = null }
) => { };

existingFunction({ firstName: "John", lastName: "Smith" }); // okay

Playground link to code

CodePudding user response:

This way:

const existingFunction = ({ firstName = null, lastName = null }:
  {firstName?: string | null, lastName?: string | null}) => {}
  • Related