Answer the question
In order to leave comments, you need to log in
How can you restrict an interface to only methods?
I have a system for IPC (Inter Process Communications) in my application. All types of communication are divided into different services. I have described the interfaces for each service, there is a dictionary of all services and a function that, by name, returns a specific service.
Roughly, it looks like this:
// Интерфейс для одного сервиса
interface Service_FOO {
methodFoo: () => void
}
// Интерфейс для другого сервиса
interface Service_BAR {
methodBar: () => void
propertyBar: boolean // <-- Должно привести к ошибке
}
// Словарь всех сервисов и их названий
interface ServiceMap {
'Service_FOO': Service_FOO
'Service_BAR': Service_BAR // <-- Или привести к ошибке здесь
}
// Функцыя которая создаёт и возвращает сервис
function createClient<T extends keyof ServiceMap>(name: T) : ServiceMap[T] {
return {} as ServiceMap[T]
}
// Пользовательский код
const serviceFoo = createClient('Service_FOO')
serviceFoo.methodFoo()
const serviceBar = createClient('Service_BAR')
serviceBar.propertyBar // Приведёт к ошибке в рантайме
createClient
all services can only have methods. Hence my question: ServiceMap
so that it can contain only interfaces in which only methods? interface Service_FOO extends Record<string, () => void> {
methodFoo: () => void
}
interface Service_BAR extends Record<string, () => void> {
methodBar: () => void
// @ts-expect-error
propertyBar: boolean
}
// Class 'FOO' incorrectly implements interface 'Service_FOO'.
// Index signature is missing in type 'FOO'.
class FOO implements Service_FOO {
methodFoo() {}
}
Service_BAR
, but at the same time I started getting an error in the class FOO
:Class 'FOO' incorrectly implements interface 'Service_FOO'.
Index signature is missing in type 'FOO'.
Answer the question
In order to leave comments, you need to log in
Here you need a little magic:
type ClearIndex<T> = {
[ P in keyof T as string extends P ? never : P ] : T[P]
};
class FOO implements ClearIndex<Service_FOO > {
methodFoo() {}
}
Record<string, () => void>
string
() => void
Service_FOO
Service_FOO
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question