简体   繁体   中英

Type 'string | undefined' is not assignable to type 'string'

I'm starting with TypeScript and I'm having the following problem:

I have a method that updates a record in the database, defined as follows:

class Category {
  update (data: ICategory & { id: string }): Promise<ICategory & { id: string }> {
    // Do Stuff
  }
}

interface ICategory {
  id?: string
  name: string,
  icon: string,
  iconColor: string
}

Note that the id field is optional in the interface, and the method required the id to be a string, and here lies the problem: when I try to call this method with the said interface, I get the following error:

TS2345: Argument of type 'ICategory' is not assignable to parameter of type 'ICategory & { id: string; }'.
  Type 'ICategory' is not assignable to type '{ id: string; }'.
    Types of property 'id' are incompatible.
      Type 'string | undefined' is not assignable to type 'string'.
        Type 'undefined' is not assignable to type 'string'.

Even if I check that typeof obj.id === 'string' I continue to have the same error.

How can I solve this problem? As I said, I'm starting with TypeScript now, so any suggestions are welcome.

Thanks!

You can use Type Guard for that:

interface FuncData {
    id: string;
}

function test(args: FuncData) { }

interface PartialData {
    id?: string;
}

const data: PartialData = { id: 'test' };

function funcDataGuard(data: PartialData): data is FuncData {
    return data.id != null;
}

if (funcDataGuard(data)) {
    test(data);
}

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