gpt4 book ai didi

typescript - TypeScript 接口(interface)可以要求多个字符串键或值相同吗?

转载 作者:行者123 更新时间:2023-12-04 01:07:47 28 4
gpt4 key购买 nike

假设我想创建一个 interface看起来像这样:

interface ColorPalette {
defaultColorName: string // should exist in colors below
colors: {
[colorName: string]: string // associate a color name to a color (hex string)
}
}
换句话说,这个调色板概念允许指定一个颜色列表(其中每个都可以通过任意颜色名称访问),但也提供默认颜色。
我想知道是否可以在 TypeScript 中强制 defaultColorName 的值存在于键/值对象中 colors ,因为指定 colors 中不存在的默认颜色是没有意义的.
我知道如果颜色名称是字符串联合,例如 type ColorType = 'bright' | 'dark' | 'subtle',这将如何工作然后我可以将泛型与 interface 一起使用,例如 interface ColorPalette<T extends ColorType> .在这种情况下,颜色名称是任意的 string那可以是任何东西。
我正在使用调色板的概念来演示我想要做什么,我的实际用例并不特定于颜色。

最佳答案

这里的关键因素是:

In this case, the color names are arbitrary strings that could be anything.


由于这个规定,您所要求的内容是不可能的,因为您要求 TypeScript 编译器(令人惊讶的是仅在编译时存在的东西)根据运行时发生的事情(插入任意字符串键/值)做出决定配对到 colors 对象中)。

关于typescript - TypeScript 接口(interface)可以要求多个字符串键或值相同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65837084/

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