Home > Blockchain >  How to reassign the type object to string in TypeScript
How to reassign the type object to string in TypeScript

Time:07-14

I have tried to reassign the property type to string, but if I reassign the property "type" to string, TypeScript throws an error

Type 'string' is not assignable to type '{ title: { value: string; }; }'.

If anyone knows the answer, kindly share your answer.

const temp= {
  type: {
      title: {
          value: "text"
      }
  }
}

temp.type=temp.type.title.value

I have shared a screenshot,of What I tried to find the answer

CodePudding user response:

typescript prohibits doing that. You need to rethinking your task, because you are doing something wrong.

As says official site "TypeScript is a strongly typed programming language...". among other things it means variable is associated with the type at the time of declaration and the type cannot be changed later.

When you write

let foo = {
  title: {
    value: "text"
  }
};

typescript now knows that foo type is object that consists of one property "title" with value type object that consists of one property "value" with value type string.

type T = {
  title: {
    value: string
  }
}

When you write

foo = "string"

typescript compares two types T and string. Type T is not string. Here you got the type error.

CodePudding user response:

As Jared Smith wrote in the comment

The type of temp.type is { title: { value: string } }. You can't change it to just string, that defeats the whole point of a type system. Make a new, different object that is of the correct type where it's type property is just a string

Just to add more to this. You can create a type that allows reassign like this:

type Temp = {
  type: string | {
    title: {
      value: string;
    }
  }
}
const temp: Temp = {
  type: {
      title: {
          value: "text"
      }
  }
}

But there is probably no reason to do this.

  • Related