Reputation: 375
I have a Locale interface that defines a locale, which is the State of my component:
interface Locale {
src: string;
alt: string;
language: string;
i18nFormat: string;
}
While debbuging the code, i'm using .toSource()
, a built-in function that allows visualizing objects content on alerts:
alert(locale.toSource())
The alert works but React+tsx throw an error:
Property 'toSource' does not exist on type 'Locale'
I tried typing toSource
as a function:
interface Locale {
src: string;
alt: string;
language: string;
i18nFormat: string;
toSource: function;
}
However it throws an Unexpected error: Cannot find name 'function'.ts(2304)
.
How do I do this?
Upvotes: 0
Views: 112
Reputation: 2870
Thanks to people answered in comment. To use a function in typescript, the correct way is () => <return type>
instead of function
keyword.
interface Locale {
src: string;
alt: string;
language: string;
i18nFormat: string;
toSource: () => void; //void if function return nothing.
}
use void
if function return nothing, or correct type like string
or number
of it return so, or if you're unsure, then use unknown
.
Hope it will work.
Upvotes: 1
Reputation: 1099
you can write it like this:
type toSourceType = (blahblah?: any) => string;
interface Locale {
src: string;
alt: string;
language: string;
i18nFormat: string;
toSource: toSourceType;
}
and also can write that type into separate type
to make a pretty abstraction.
Upvotes: 2