0

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)

cbutler
  • 833
  • 13
  • 36
  • Does this answer your question? [Global types in typescript](https://stackoverflow.com/questions/42984889/global-types-in-typescript) – captain-yossarian from Ukraine Sep 23 '21 at 09:50
  • I think this is what I am looking for but I am getting an error when I try to define the interface. if I say interface Char { char: Char; } then I get an error in my Char class that string is not assignable to Char. hmmm – cbutler Sep 23 '21 at 11:01
  • Could give a code sample of how to define the interface? – cbutler Sep 23 '21 at 11:40
  • please share your interface and what error do you have? – captain-yossarian from Ukraine Sep 23 '21 at 11:42
  • I've updated my question with code – cbutler Sep 23 '21 at 12:38
  • 1
    So you are defining a global interface Char, which is a small object that has a property named `char`, which has the type `Char`? this seems a bit crazy? – Evert Sep 23 '21 at 12:50
  • Wait, what are you trying to achieve with this code? Is the `char` property supposed to be a `string` or a `Character`? If the former, then your `Char` interface is defined wrong. If the latter, then `Character` is implemented wrong. If neither, or both, or something else, then you should probably explain very carefully and explicitly because right now it sounds contradictory. What is the `Char` type going to do? It might help to show a [mre] with use cases in [The TypeScript Playground](https://tsplay.dev/WPjezN) or a web IDE of your choosing. – jcalz Sep 23 '21 at 14:22
  • My goal was to create a Type of Character which is exactly one letter. I am not being overly strict with the definition, I just want to be able tp specify a Character in an interface and be able to pass in a string with length of 1 char without error but a string of more than one would cause an error. Is that clear? – cbutler Sep 23 '21 at 15:00

0 Answers0