6 ms·
type RobotName = string; function foo(r: RobotName) {} ?
by jzig 4y ago
type RobotName = string;
function foo(r: RobotName) {}
?
- chpatrick 4y agoIn TypeScript any type that's structurally the same is considered equal, type just gives it a different name.
- Waterluvian 4y agoYep. 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.
- roflyear 4y agoYeah 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.
- tazard 4y agoIf 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?
- roflyear 4y agoI 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.
- tshaddox 4y ago> 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.