lastnigtic
lastnigtic

Reputation: 35

Why typescript treat a specific string as a string in class properties?

Here is the example:

type a = {
    b: '123'
}[]

class Test {
    public t:a = []
}


class SubTest extends Test {
    public t = [{
        b: '123' // error, Type 'string' is not assignable to type '"123"'
    }]
}

Is there a way to make SubTest passing typecheck without change interface a?

Upvotes: 0

Views: 48

Answers (2)

Ravenscar
Ravenscar

Reputation: 2880

add as const

class SubTest extends Test {
  public t = {
      b: '123'
  } as const
}

or

class SubTest extends Test {
  public t = {
      b: '123' as const
  }
}

this is also useful if you want to do things like derive a type from an array of strings, e.g.:

const x = ["foo", "bar"];
type tx = typeof x; // string[]

const y = ["foo", "bar"] as const;
type ty = typeof y; // readonly ["foo", "bar"]

Upvotes: 1

nyarthan
nyarthan

Reputation: 535

Since you already have property 't' in 'Test' you can not reassign it when extending. Change the property name in 'SubTest' to something other then 't' and it will work.

type a = {
  b: "123";
};

class Test {
  public t: a = {
    b: "123",
  };
}

class SubTest extends Test {
  public x: a = {
    b: "123",
  };
}

Upvotes: 0

Related Questions