Typescript-将类型信息赋予并从同一对象中提取类型信息



假设我正在与声音设计师合作,希望他们在编辑配置文件时获得良好的信息。我认为下面的@eventsA可以很好地实现这个目的。但是,我也想从这些dev的配置中获得应用程序其余部分的良好类型信息,然后我认为@eventsB工作得很好。我怎样才能两全其美?当编辑配置文件并且能够从配置中提取特定类型以在应用程序的其余部分中使用时,这是错误的。

interface IEvent {
id: string
actions: Array<{
func: "setMasterVolume" | "playSound",
args: Array<string | number | boolean>
}>
}
// With type that is helpfull for sound designer
const eventsA: Array<IEvent> = [
{
foo: "bar", // this line will give error to sound designer because not in interface
id: "start",
actions: [
{
func: "setMasterVolume",
args: [ 1 ]
}
]
},
{
id: "stop",
actions: [
{
func: "setMasterVolume",
args: [ 0 ]
}
]
}
]
// This only gives unspecific 'string' type
type AudioEventsA = typeof eventsA[number]['id']
// With type that is helpfull for developer
const eventsB = [
{
foo: "bar", // now no error on this line unfortunately
id: "start",
actions: [
{
func: "setMasterVolume",
args: [ 1 ]
}
]
},
{
id: "stop",
actions: [
{
func: "setMasterVolume",
args: [ 0 ]
}
]
}
] as const
// Now I can extract type of: 'start' | 'stop' rather than just string.
type AudioEventsB = typeof eventsB[number]['id']

那么,如何在:foo:"条";得到AudioEvents = 'start' | 'stop'

我认为您可以让您的接口接受预期的类型generics。由于您允许您的开发人员使用const assertions创建阵列,因此您必须将您的阵列作为readonly。要指定允许开发人员创建哪些类型的数组,可以创建类型Iarr,然后他们将他们决定的数组所需的类型传递给它。

export type Func = "setMasterVolume" | "playSound";
interface IEvent<T extends string, F extends Func, A extends string | number | boolean> {
id: T
actions: readonly{
func: F,
args: readonly A[]
}[]
}
export type Iarr = readonly IEvent<'start'|'stop', "setMasterVolume", number>[];
// With type that is helpfull for sound designer
const eventsA: Iarr = [
{
foo: "bar", // this line will give error to sound designer because not in interface
id: "start",
actions: [
{
func: "setMasterVolume",
args: [ 1 ]
}
]
},
{
id: "stop",
actions: [
{
func: "setMasterVolume",
args: [ 0 ]
}
]
}
]
// This only gives unspecific 'string' type
type AudioEventsA = typeof eventsA[number]['id']
// With type that is helpfull for developer
const eventsB: Iarr = [
{
foo: "bar", // now no error on this line unfortunately
id: "start",
actions: [
{
func: "setMasterVolume",
args: [ 1 ]
}
]
},
{
id: "stop",
actions: [
{
func: "setMasterVolume",
args: [ 0 ]
}
]
}
] as const
// Now I can extract type of: 'start' | 'stop' rather than just string.
type AudioEventsB = typeof eventsB[number]['id']

最新更新