How do I declare a read-only array tuple in TypeScript?

前端 未结 6 1628
太阳男子
太阳男子 2020-12-17 15:07

We can declare a typed tuple in TypeScript, for example, with the type annotation [string, number]. This means an array of 2 elements where the first element ne

6条回答
  •  生来不讨喜
    2020-12-17 15:41

    Solution in Typescript 3.4: Const Contexts

    It looks like there will be a clean solution for this requirement coming with TypeScript 3.4 version:

    With so-called const contexts, the compiler can be told to treat an array or an object as immutable, meaning that their properties are read-only. This also allows the creation of literal tuple types with narrower type inference (i.e. your ["a", "b"] can for the first time be of type ["a", "b"], not string[] without specifiying the whole thing as a contextual type)

    The syntax will look like this:

    let foo = ["text", 1] as const
    

    or

    let foo =  ["text", 1]
    

    Here is the extended information of the corresponding PR. As of now, the feature should be available in typescript@next.

提交回复
热议问题