0

I am looking for a way to make this code below fail.

When I create these In and Out types I'd love to have any strings passed into usage to have to be cast as In. Is this possible?

type In = string;
type Out = string;

const usage = (x: In): Out => 'meow';

usage('hi');
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • 1
    related: https://stackoverflow.com/questions/49260143/how-do-you-emulate-nominal-typing-in-typescript and https://stackoverflow.com/questions/37053800/typescript-specific-string-types – artem Jan 04 '19 at 21:09

1 Answers1

0

I think for this we may have to create our own type instead of using the string type. The type keyword in ts is just an alias for the types used, more details here -

https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#3.10

So the above code is same as :

const usage = (x: string): string=> 'meow';

In case you are looking for some method that takes some object having a string property;

type In = {text:string};
type Out = string;

const usage = (x: In): Out => 'meow';
const data: In = { text: 'value' };
usage(data);
Vishnu
  • 897
  • 6
  • 13