0

I want to define a type in TypeScript, which among other keys has the key "description". The key should not be optional, the associated value should be allowed to be a string or null.

I tried to define my type like this:

type Form = {
    id: string
    name: string
    description: string | null
}

Unfortunately, ESLint returns me this message:

Usage of "null" is deprecated except when describing legacy APIs; use "undefined" instead

If I declare description as undefined, but also the key becomes optional or not?

How to define the type so that this object is OK

const questions: Form = {
    id: 'q1',
    name: 'Test',
    description: null
}

but not this one:

const questions: Form = {
    id: 'q1',
    name: 'Test'
}

and also not this one:

const questions: Form = {
    id: 'q1'
}
Siddi
  • 984
  • 10
  • 19
  • Does this answer your question? [How to declare a type as nullable in TypeScript?](https://stackoverflow.com/questions/17220114/how-to-declare-a-type-as-nullable-in-typescript) – mgm793 Jan 13 '23 at 09:31
  • 3
    This warning is *not* coming from the TypeScript compiler. You must have some other 3rd party linter which produces this warning. Usage of `null` is perfectly fine and the type in the question should work as is. – Tobias S. Jan 13 '23 at 09:36
  • You are right, the message comes from eslint – Siddi Jan 13 '23 at 09:41
  • I think this (https://stackoverflow.com/questions/17220114/how-to-declare-a-type-as-nullable-in-typescript ) does not answer my question, because the last example should not be OK (key "name") missing. – Siddi Jan 13 '23 at 09:46
  • Are you using https://github.com/googleapis/rushstack/blob/24fe26a6ef6619c1071d39d1b6de69bcf4782473/stack/eslint-plugin/src/no-new-null.ts#L19? – Sam Chen Jan 13 '23 at 13:38
  • Yes, I am using the Microsoft Rushstack compiler (SharePoint SPFX development) – Siddi Jan 16 '23 at 07:29

1 Answers1

1

Your typings are correct. It's ESlint that's giving the error. You can make ESLint happy by using undefined


type Form = {
    id: string
    name: string
    description: string | undefined
}

const questions1: Form = {
    id: 'q1',
    name: 'Test',
    description: undefined
}

// Will have an error
const questions2: Form = {
    id: 'q1',
    name: 'Test'
}

// Will have an error
const questions3: Form = {
    id: 'q1'
}

Note that defining a type for a field like description: string | undefined doesn't make it optional but description?: string does

May Rest in Peace
  • 2,070
  • 2
  • 20
  • 34