【问题标题】:Use a generic string as the key of an object使用通用字符串作为对象的键
【发布时间】:2019-05-29 14:28:19
【问题描述】:

我想定义一个对象O,它在某个类型参数T extends string上是通用的,这样对象O总是有一个值为T的键。

type O<T extends string> = { [t in T]: string };

function f<T extends string>(t: T, o: O<T>) {
    const x = o[t];
    return x === "hello";
}

let s = f("a", { a: "" })

if (s === "Hello") {

}

这是我尝试过的,但它实际上不起作用,因为O[T] 没有被推断为字符串。这意味着最后一个 if 有错误,因为 TypeScript 的比较总是false

TypeScript Playground Link

【问题讨论】:

  • 什么不完全有效?该代码中没有错误,如果您想要像 const x: string = o[t] 一样注释 x 并且没有错误。问题出在哪里?
  • 我的问题是必须注释才能获得正确的类型。
  • 您没有对其进行注释,但您可以这一事实意味着编译器确实理解O&lt;T&gt;[T]可分配给string。如果您的问题是在 IntelliSense 中检查 x 的类型会显示 O&lt;T&gt;[T] 而不是 string,那么您的问题应该解释为什么这对您来说是个问题。仅仅是美学吗?或者某些地方的代码是否真的因为差异而中断?现在我只看到“它不起作用”和“我不喜欢它”,而不是 minimal reproducible example,所以很难知道如何在这里进行。祝你好运!
  • 问题是不分配给字符串确实会导致下面的错误。抱歉,我应该在问题本身中说明这一点。我编辑了这个问题以反映这一点。无论如何,我似乎很清楚分配给字符串是唯一有效的解决方案。

标签: typescript


【解决方案1】:

O[T] 不会直接显示为string,但在所有意图和目的上都会表现为string

type O<T extends string> = { [t in T]: string };

function f<T extends string>(t: T, o: O<T>) {
    let x = o[t];
    let s: string = x; // assignable to string 
    x = "S" // string can be assigned to it
    return x;
}
let s: string = f("a", {a: ""}) // outside it is string

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多