将泛型与索引类型相结合

men*_*fon 5 typescript

由于这有效:

const f = <T extends string>(x: T) => x;
f("");

interface Dictionary<T> { [key: string]: T; }
const dict: Dictionary<number> = { a: 1 };
Run Code Online (Sandbox Code Playgroud)

我期待以下代码也能正常工作:

interface MyRecord<Key extends string, Value> { [_: Key]: Value };
Run Code Online (Sandbox Code Playgroud)

但编译器报告_:

An index signature parameter type must be 'string' or 'number'.
Run Code Online (Sandbox Code Playgroud)

改变Key extends string到Key extends string | number什么也不做(同样的错误)。

它失败的原因是什么以及如何寻找正确的解决方案?(最好不使用Any和类似。)

编辑1:

type XY = 'x' | 'y';
const myXY: XY = 'x';
const myString: string = myXY;
Run Code Online (Sandbox Code Playgroud)

由于这有效,我假设与索引类型相同(stringcan 的子集扮演string索引类型所需的角色)。

jca*_*alz 7

我们来谈谈索引签名类型和映射类型。它们具有相似的语法并做类似的事情,但它们并不相同。以下是相似之处:

  • 它们都是表示一系列属性的对象类型

  • 语法:索引签名和映射类型都在对象类型中使用括号中的类键表示法,如 {[Some Key-like Expression]: T}

现在的差异:

索引签名

索引签名描述了对象类型或接口的一部分,代表任意数量的相同类型的属性,具有来自特定键类型的键。目前,此密钥类型只有两种选择:string、 或number。

  • 语法:索引签名的语法如下所示:

    type StringIndex<T> = {[dummyKeyName: string]: T}
    type NumberIndex<T> = {[dummyKeyName: number]: T} 
    
    Run Code Online (Sandbox Code Playgroud)

    有一个虚拟键名(dummyKeyName上面),它可以是任何你想要的,并且在括号之外没有任何意义,后跟一个类型注释(:)string或number。

  • 对象类型的一部分:索引签名可以与对象类型或接口中的其他属性一起出现:

    interface Foo {
      a: "a",
      [k: string]: string
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 任意数量的属性:一个可索引类型的对象不需要为每个可能的键都拥有一个属性(对于对象string或number除了Proxy对象,这甚至是不可能的)。相反,您可以将包含任意数量的此类属性的对象分配给可索引类型。请注意,当您从可索引类型读取属性时,编译器将假定该属性存在(与 相对undefined),即使--strictNullChecks启用了 ,即使这不是严格的类型安全。例子:

    type StringDict = { [k: string]: string };
    const a: StringDict = {}; // no properties, okay
    const b: StringDict = { foo: "x", bar: "y", baz: "z" }; // three properties, okay
    const c: StringDict = { bad: 1, okay: "1" }; // error, number not assignable to boolean
    
    const val = a.randomPropName; // string
    console.log(val.toUpperCase()); // no compiler warning, yet
    // "TypeError: val is undefined" at runtime
    
    Run Code Online (Sandbox Code Playgroud)
  • 相同类型的属性:索引签名中的所有属性必须是相同类型的;类型不能是特定键的函数。因此,“属性值与其键相同的对象”不能用索引签名表示为比{[k: string]: string}. 如果你想要一个接受{a: "a"}但拒绝的类型{b: "c"},你不能用索引签名来做到这一点。

  • Only stringor numberis allowed as the key type: 目前您可以使用string索引签名来表示类似字典的类型,或使用number索引签名来表示类似数组的类型。就是这样。您不能将类型扩大到string | number或缩小到特定的一组string或number文字,如"a"|"b"或1|2。(您关于为什么它应该接受更窄的集合的推理是合理的,但这不是它的工作原理。规则是“索引签名参数类型必须是 string或number”。)已经做了一些工作来放宽此限制并允许任意键类型在索引签名中,请参阅 microsoft/TypeScript#26797,但至少目前似乎已停止。

映射类型

另一方面,映射类型描述了一个完整的对象类型,而不是一个接口,它 表示一组可能不同类型的特定属性,具有来自某个键类型的键。 您可以为此使用任何键类型,尽管文字的联合是最常见的(如果您使用stringor number,那么映射类型的那部分会变成...你猜怎么着?索引签名!)在接下来的内容中,我将只使用作为键集的文字联合。

  • 语法:映射类型的语法如下所示:

    type Mapped<K extends keyof any> = {[P in K]: SomeTypeFunction<P>};
    type SomeTypeFunction<P extends keyof any> = [P]; // whatever
    
    Run Code Online (Sandbox Code Playgroud)

    P引入了一个新的类型变量,它遍历in键集合的每个成员K。新类型变量仍在属性 value 的范围内SomeTypeFunction<P>,即使它在括号之外。

  • 完整的对象类型:映射类型是完整的对象类型。它不能与其他属性一起出现,也不能出现在界面中。它就像一个联合或交叉类型:

    interface Nope {
        [K in "x"]: K;  // errors, can't appear in interface
    }
    type AlsoNope = {
        a: string,
        [K in "x"]: K; // errors, can't appear alongside other properties
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 一组特定的属性:与索引签名不同,映射类型必须在键集中的每个键都具有一个属性。(例外情况是,如果该属性恰好是可选的,要么是因为它是从具有可选属性的类型映射的,要么是因为您使用?修饰符将属性修改为可选的):

    type StringMap = { [K in "foo" | "bar" | "baz"]: string };
    const d: StringMap = { foo: "x", bar: "y", baz: "z" }; // okay
    const e: StringMap = { foo: "x" }; // error, missing props
    const f: StringMap = { foo: "x", bar: "y", baz: "z", qux: "w" }; // error, excess props
    
    Run Code Online (Sandbox Code Playgroud)
  • 属性类型可能会有所不同:因为迭代键类型参数在属性类型的范围内,您可以将属性类型作为键的函数进行更改,如下所示:

    type SameName = { [K in "foo" | "bar" | "baz"]: K };
    /* type SameName = {
        foo: "foo";
        bar: "bar";
        baz: "baz";
    } */
    
    Run Code Online (Sandbox Code Playgroud)
  • 可以使用任何键集:您不限于string或number。您可以使用任何一组string文字或number文字,甚至是symbol值(但这些使用起来更加复杂,所以我忽略了这一点)。您也可以在那里使用string或number,但是当发生这种情况时,您会立即获得索引签名:

    type AlsoSameName = { [K in "a" | 1]: K };    
    /* type AlsoSameName = {
        a: "a";
        1: 1;   
    } */
    const x: AlsoSameName = { "1": 1, a: "a" }
    
    type BackToIndex = { [K in string]: K }
    /* type BackToIndex = {
        [x: string]: string;
    }*/
    const y: BackToIndex = { a: "b" }; // see, widened to string -> string
    
    Run Code Online (Sandbox Code Playgroud)

    由于可以使用任何键集,它可以是通用的:

    type MyRecord<Key extends string, Value> = { [P in Key]: Value };
    
    Run Code Online (Sandbox Code Playgroud)

所以这就是你要做的MyRecord。它不能是可索引的类型;只有一个映射类型。请注意,内置Record<K, T>实用程序类型本质上是相同的(允许K extends string | number | symbol),因此您可能希望使用它而不是您自己的。

好的,希望有帮助;祝你好运!

代码链接