首页 > 解决方案 > 为什么打字稿将特定字符串视为类属性中的字符串?

问题描述

这是示例:

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

有没有办法在SubTest不改变的情况下通过类型检查interface a

标签: typescripttypescript-typings

解决方案


添加as const

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

或者

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

如果您想做一些事情,例如从字符串数组派生类型,这也很有用,例如:

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

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

推荐阅读