简体   繁体   中英

How to define an TypeScript object where an key should be available and the value should be a string or null?

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'
}

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 description: string | undefined doesn't make it optional but description?: string does

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM