nbd-wtf / nostr-tools

Tools for developing Nostr clients.
The Unlicense
685 stars 188 forks source link

export from nostr-tools the specialized types written in nip19 #408

Open antonioconselheiro opened 3 months ago

antonioconselheiro commented 3 months ago

I'm suggesting that specialized types written in nip19 code be exposed from nostr-tools as named symbols. The nprofile, nrelay, nevent, naddr, nsec, npub, note, ncryptsec types and a Nip05 type would be very useful to strengthen the types in nostr apps.

Today I'm using like this:

export type TNostrPublic = `npub1${string}`;
export type TNostrSecret = `nsec1${string}`;
[...]
export type TNip05 = `${string}@${string}`;

but surelly you would like another name

antonioconselheiro commented 3 months ago

Would be too much to suggest to include too typescript type predicates for these exclusive types?

export const nostrTypePredicate = {

  isNostrSecret(nsec: string): nsec is TNostrSecret {
    return /^nsec/.test(nsec);
  }

  isNostrPublic(npub: string): npub is TNostrPublic {
    return /^npub/.test(npub);
  }

  isNcryptsec(ncryptsec: string): ncryptsec is TNcryptsec {
    return /^ncryptsec/.test(ncryptsec);
  }
}

The type predicate has cast effect, if the string passes in the if with this type guard, it will be recognized by typescript as the specialized type.

image

fiatjaf commented 3 months ago

I don't know if we gain anything by doing this, but if it doesn't hurt we can have it.

antonioconselheiro commented 3 months ago

I'm available to implement this, I'll present a pr of this later