【问题标题】:Typescript pass variable as generic type parameter打字稿传递变量作为泛型类型参数
【发布时间】:2021-06-17 10:53:53
【问题描述】:

我有一个函数,它接受字符串或字符串数​​组并返回一个带有这些字符串键的对象。

这是虚拟函数:

type myType<T extends string> = { [K in T]: string }
const myFunc = <T extends string>(param: T | T[]): myType<T> => {
    let result = <myType<T>>{}
    // some codes here...
    return result;
}

通过上面的代码,我已经实现了:

let val = myFunc(['foo', 'bar']);
val.foo // valid
val.other // invalid

但是如果我将一个变量传递给函数,那么所有的字符串键都是有效的:

let variable = ['foo', 'bar'];
let val = myFunc(variable);
val.foo // valid
val.other // valid

是否有解决方法,以便我可以传递变量但仍按预期工作?

【问题讨论】:

  • 我认为你需要类似string extends T ? never : 的东西,但我不知道它的语法是什么

标签: typescript typescript-typings typescript-generics


【解决方案1】:

当您创建变量let variable = ['foo', 'bar'] 时,variable 的类型变为string[],并且您失去了数组中特定字符串的知识。您需要使用as const 以便Typescript 将variable 解释为字符串文字'foo''bar' 的固定元组。由于这个固定元组是readonly,你还需要修改你的函数来接受readonly数组。

const myFunc = <T extends string>(param: T | readonly T[]): myType<T> => {
let variable = ['foo', 'bar'] as const;
let val2 = myFunc(variable);
val2.foo // valid
val2.other // invalid

Typescript Playground Link

【讨论】:

  • 有没有办法不使用as const?很容易忘记添加,也没有报错。
  • 你可以直接将它传递给函数,但你已经说过你不想这样做。您可以指定显式类型let variable: ['foo', 'bar'] = ['foo', 'bar']
猜你喜欢
  • 2022-11-11
  • 2018-05-02
  • 1970-01-01
  • 1970-01-01
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2019-03-05
相关资源
最近更新 更多