Hacker Read top | best | new | newcomments | leaders | about | bookmarklet login

type RobotName = string;

function foo(r: RobotName) {}

?



view as:

In TypeScript any type that's structurally the same is considered equal, type just gives it a different name.

Yep. But that function will accept

type RobotUuid = string;

const bar: RobotUuid = “abc…”;

foo(bar);

This is what duck typing is and specifically my curiosity about being able to de-duck on demand.


Yeah just means you have to rely on linting and your ide to catch those errors. And hopefully the rest of your team does the same thing.

Tho I suppose if it is really important you can put an assert there but I'm not familiar with that wrt typescript, maybe the transpiler would kill that?

I've done the occasional type checking in that way in similar languages, it is kind of self documenting too. 90% of the time duck typing is what you want.


If robot0 name is AAA and uid Is BBB, and robot 1 name is BBB and uid AAA, and you call the function checkRobot('AAA'), what sort of assert exactly could differentiate between a name and a uid?

I don't think it is possible in Typescript, but in other languages you can do assertations about custom types. Like

assert istype(whatever, MyCustomType)

Which would throw an exception if whatever is not a "MyCustomType" at runtime.


> Yeah just means you have to rely on linting and your ide to catch those errors. And hopefully the rest of your team does the same thing.

Yes, and that’s roughly what TypeScript is: a linter that everyone on your team is running.


Legal | privacy