Skip to content

Brand string types #185

Description

@Akuukis

Problem

Many data structures are represented as strings, and types don't help much because string matches string. E.g.

  • at some places it is confusing whenever you need an address of existing account, random publicKey or just a string.
  • when any typeguarded XDR is serialized and then parsed again, it again loses it's narrowed type
  • Typescript wont catch if I'm messing up any of the following: PublicKey, Address, AccountId, Secret, Transaction hash, serialized transaction, signature, and perhaps more.

Describe the solution you'd like

I propose to brand all those strings. That way TypeScript compiler can pick up all the problems. Something like this:

import { Brand } from 'utility-types';

type PublicKey = Brand<string, "PublicKey">
type Secret = Brand<string, "Secret">
// ...

class Keypair {
    static fromSecret(secret: Secret): PublicKey
    //...
}

const publicKey = Keypair.fromSecret(Secret)
Keypair.fromSecret(publicKey)  // <-- TypeScript will complain here.

This even has potential to track the narrowed types through serialization if needed.

Describe alternatives you've considered

Less strict alternative is to use simple aliases and excessive comments.

/**
 * Do not pass where Secret is expected, please!!!
 */
type PublicKey: string

Related: #176, DefinitelyTyped/DefinitelyTyped#32025

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions