打字稿:将字符串数组转换为字符串文字

时间:2019-04-02 08:39:48

标签: typescript

我想将货币代码列表转换为字符串文字。它具有设置const断言以生成字符串文字的功能。 Typescript 3.4。以下代码有效

let ccs = <const>['INR', 'USD']
type CurrencyCode = typeof ccs[number]
let cc: CurrencyCode = 'PKR'

它引发错误Type '"PKR"' is not assignable to type '"INR" | "USD"'

但是以下代码不会引发任何错误。为什么会这样呢?我应该进行哪些更改以确保函数的输出可以转换为字符串文字?

function getCurrencyCodes() {
  return ['INR', 'USD']
}

let val: string[] = getCurrencyCodes()
let ccs = <const>[...val]
type CurrencyCode = typeof ccs[number]
let cc: CurrencyCode = 'PKR'

1 个答案:

答案 0 :(得分:0)

Typescript不是运行时语言。

第二个代码不起作用,因为您使用的是witch函数,将在运行时对其进行评估。

使用const typescript时可以说出确切的类型。没有功能

function getCurrencyCodes(): ['INR', 'USD'] {
  return ['INR', 'USD'];
}

const val = getCurrencyCodes();
const ccs = [...val];
type CurrencyCode = typeof ccs[number];
const cc: CurrencyCode = 'PKR'; // here you got error

因为函数类型是const可以通过打字稿来缩小 如果您要返回string [],则打字稿不能缩小确切的文字类型

相关问题