gpt4 book ai didi

typescript :记录<>,其中值取决于键

转载 作者:行者123 更新时间:2023-12-01 21:40:46 26 4
gpt4 key购买 nike

我想写这样的东西:

const structs: Record<T extends StructureConstant,Array<ConcreteStructure<T>>> = Object.create(null);

其中 StructureConstant 是常量的联合,而 ConcreteStructure 基本上是一个 type lookup .

这在 TypeScript 中可行吗?我不知道如何使值依赖于键。


这是一个完整的例子:

type StructureConstant = "road" | "tower";

interface Road {
a: "i am a road",
}

interface Tower {
b: "i be towerin"
}

type ConcreteStructure<T extends StructureConstant> = T extends "road"
? Road
: T extends "tower"
? Tower
: never;

type StuctureRecord<T extends StructureConstant> = Record<T, Array<ConcreteStructure<T>>>

const structs: StuctureRecord<StructureConstant> = Object.create(null);

const roads = structs["road"]; // should be Array<Road>|undefined

console.log(roads[0].a); // should work (if structs was populated)

TS playground

最佳答案

在 typescript 中,只有函数值可以具有泛型类型。其他值需要完全指定。

所以也许你想要这样的东西:

type StuctureRecord<T extends StructureConstant> = Record<T, Array<ConcreteStructure<T>>>

// structs doesn't have a generic type.
const structs: StuctureRecord<StructureConstant> = Object.create(null);

// function can have generic type.
const structsCreator = <T extends StructureConstant>(): Record<T, Array<ConcreteStructure<T>>> => Object.create(null)

const structs = structsCreator<StructureConstant>()

Playground


要获得描述的效果,您不能使用 Record。记录将所有键映射到同一类型。如果每个条目需要不同的类型,则需要自定义映射类型

type StuctureMappedType<T extends StructureConstant> = 
{ [K in T]: Array<ConcreteStructure<K>>}

Playground

关于 typescript :记录<>,其中值取决于键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61403758/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com