不能用于索引类型

不能用于索引类型

本文介绍了为什么我不能使这种类型通用?输入“x"不能用于索引类型“y";ts(2536)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个泛型类型,它采用根级属性名称并返回嵌套在其下的属性的联合类型.例如:

I'm trying to write a generic type which takes a root-level property name and returns a union type of a property nested underneath it. For example:

interface operations {
  updateSomething: {
    "201": {
      schema: number;
    };
    "400": {
      schema: string;
    };
  };
}

如果我想获得模式"对于 updateSomething 类型,它应该解析为 number |字符串.非通用版本工作正常:

If I want to get the "schemas" for the type updateSomething, it should resolve to number | string. The non-generic version works fine:

type UpdateSomethingSchema =
  operations["updateSomething"][keyof operations["updateSomething"]]["schema"];

// string | number ✓

我尝试编写泛型类型是:

My attempt at writing a generic type is:

type SchemaOf<
  O extends keyof operations
> = operations[O][keyof operations[O]]["schema"];

但这给了我一个错误:

Type '"schema"' cannot be used to index type 'operations[O][keyof operations[O]]'.ts(2536)

有趣的是,如果我忽略错误,该类型似乎确实有效:

Interestingly, if I ignore the error, the type does seem to work:

type UpdateSomethingSchema = SchemaOf<"updateSomething">;

// string | number ✓

我做错了什么,还是 TypeScript 的限制?

Am I doing something wrong, or is this a limitation of TypeScript?

推荐答案

你可以借助分布式条件类型来实现:

You can achieve it with help of distributive conditional types:


type Schema<T> = {
  schema: T
}


interface operations {
  updateSomething: {
    "201": Schema<number>;
    "400": Schema<string>;
  };
}

type SchemaOf<
  O extends keyof operations
  > = operations[O][keyof operations[O]] extends Schema<infer S> ? S : never

type Result = SchemaOf<'updateSomething'> // string | number

IF operations[O][keyof operations[O]] 推断具有 schema 属性的对象,TypeScript 能够推断出 schema 的类型:T 并且由于分布性,它将返回联合类型.

IF operations[O][keyof operations[O]] infers to object with schema property, TypeScript is able to infer the type of schema: T and because of distributivity, it will return a union type.

分布式条件类型文档

这篇关于为什么我不能使这种类型通用?输入“x"不能用于索引类型“y";ts(2536)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 05:42