最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论