Typescript Readonly<T> not working on primitives - Stack Overflow

Why does the Readonly<T> utility type only function on non-primitive types? And is there a way fo

Why does the Readonly<T> utility type only function on non-primitive types? And is there a way for me to have it work also on primitive types?

function inspect<T>(inspector: (val: Readonly<T>) => void): void {
  // Do something...
}

function run() {
  inspect<string>((str: string) => {
    str = `New string` // Can change
  })

  inspect<number>((num: number) => {
    num = 12 // Can change
  })

  inspect<boolean>((bool: boolean) => {
    bool = true // Can change
  })

  inspect<{str: string, num: number, bool: boolean}>((obj) => {
    obj.str = `New string` // Can't change; yields compile time error
    obj.num = 12 // Can't change; yields compile time error
    obj.bool = true // Can't change; yields compile time error
  })
}

Playground

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745269341a4619648.html

相关推荐

  • Typescript Readonly&lt;T&gt; not working on primitives - Stack Overflow

    Why does the Readonly<T> utility type only function on non-primitive types? And is there a way fo

    4小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信