I want to make a Char
type in TypeScript and I have defined a simple class below. Is there a way that I can use this like string
or Object
without having to import the class into every other file in my (NextJS) project?
export default class Character implements Char {
readonly char: string;
constructor(char: string) {
if (char.length !== 1) {
throw new Error(`${char} is not a character.`);
}
this.char = char;
}
toString(): string {
return this.char;
}
toUpperCase(): string {
return this.char.toUpperCase();
}
toLowerCase(): string {
return this.char.toLowerCase();
}
}
global interface:
import Character from '../models/Char';
declare global {
interface Char {
char: Character;
}
}
This results in an error: Property 'char' in type 'Character' is not assignable to the same property in base type 'Char'. Type 'string' is not assignable to type 'Character'.ts(2416)