TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Support user-defined type guard functions

Open RyanCavanaugh opened this issue 12 years ago • 85 comments

We currently only support some baked-in forms of type checking for type guards -- typeof and instanceof. In many cases, users will have their own functions that can provide run-time type information.

Proposal: a new syntax, valid only in return type annotations, of the form x is T where x is a declared parameter in the signature, or this, and T is any type. This type is actually considered as boolean, but "lights up" type guards. Examples:

function isCat(a: Animal): a is Cat {
  return a.name === 'kitty';
}

var x: Animal;
if(isCat(x)) {
  x.meow(); // OK, x is Cat in this block
}

class Node {
  isLeafNode(): this is LeafNode { throw new Error('abstract'); }
}
class ParentNode extends Node {
  isLeafNode(): this is LeafNode { return false; }
}
class LeafNode extends Node {
  isLeafNode(): this is LeafNode { return true; }
}
var someNode: LeafNode|ParentNode;
if(someNode.isLeafNode()) {
  // someNode: LeafNode in this block
}

The forms if(userCheck([other args,] expr [, other args])) { and if(expr.userCheck([any args])) would apply the type guard to expr the same way that expr instanceof t and typeof expr === 'literal' do today.

RyanCavanaugh avatar Oct 30 '14 21:10 RyanCavanaugh

@shelby3

I realize you are a younger man well before the precipitous drop in testosterone (starting university in 2007 versus mine in 1983) and I notice you are upvoting spiteful comments against me in other issue threads where I am participating, but really man I am 51 years old. Ego is for little people. You'll earn your stripes eventually and realize the wisdom of the linked blog.

These statements have no place in this discussion.

Btw, I appreciate your discussion (even the humorous unnecessary bravado part). You are helping me (we are helping each other) to understand the solution. Isn't that wonderful.

Indeed, I was attempting to be humorous, but I was also being serious. Stating that one is objective and not coming from any emotional place, especially after having already intimated that others are coming from an emotional place, makes one's further statements highly suspect. Yes, we are helping each other learn, and yes that is a wonderful thing.

So I maintain my stance that the feature of this issue was not necessary. And now I add a bug report that TypeScript is failing to put interfaces into prototype chain. Not fixing a bug and making an unnecessary unsound typing feature to compensate for not doing so, is a design mistake. That is what open source is for, so that with enough eyeballs someone will catch the error.

The remaining problem is that TypeScript does not support multiple inheritance of subclass through linearization of the hierarchy, so we can't currently extend from both BaseCollection and Sortable simultaneously.

In TypeScript interfaces have always been structural. They declare a compile time name for a certain shape. Not all TypeScript/JavaScript programs are class based. Consider the following code.

export function openModal(modalOptions: ModalOptions): void {
    const modal = createModalImpl(modalOptions.template, modalOptions.viewModel);
    modal.onOpen = modalOptions.onOpen;
    modal.onClose = modalOptions.onClose;
    modal.editable = modalOptions.readonly;
    modal.open();
}

export interface ModalOptions {
    template: string;
    viewModel: any;
    onOpen: (callback: () => void);
    onClose: (callback: () => void);
    readonly: boolean;
}

The purpose of the ModalOptions interface is to declare part of the interface of the function openModal so that the TypeScript compiler can check that the correct arguments are specified and so that the caller knows what to pass. It is used for both documentation and typechecking to formally describe the contract of the API, no classes are involved. Thus, the following two examples have the same behavior.

import { openModal, ModalOptions } from 'basic-modal-utilities';
import template from './template.html';

// ex 1.
const vm = {
    name: 'Bob',
    friends: ['Alice', 'Eve']
};
openModal({
    template: template,
    viewModel: vm,
    readonly: true,
    onOpen: {
        console.log(`modal opened with data ${json.stringify(vm)}.`);
    },
    onClose: () => {
        if (vm.name !== 'Bob' || 
            vm.friends[0] !== 'Alice' || 
            vm.friends[1] !== 'Eve' || 
            vm.length > 2) {
            console.error('Test failed: viewModel was modified');
        }
    }
});

// ex 2. 

class ReadonlyModalOptions implements ModalOptions {
    readonly = true;

    constructor(public viewModel, public template) { }

    onOpen() {
        console.log(`modal opened with data ${json.stringify(this.viewModel)}.`);   
    }

    onClose: () => {
        if (this.viewModel.name !== 'Bob' ||
            this.viewModel.friends[0] !== 'Alice' || 
            this.viewModel.friends[1] !== 'Eve' || 
            this.viewModel.length > 2) {
            console.error('Test failed: viewModel was modified');
        }
    }
}
const vm = {
    name: 'Bob',
    friends: ['Alice', 'Eve']
};
openModal(new ReadonlyModalOptions(vm, template));

Lots of APIs work this way. They simply require that a caller pass arguments that meets their requirements, but not how those requirements are defined. This is not only a common pattern but a useful one. If interfaces were added to the prototype chain, then it would be reasonable for someone to add the following line of code to the openModal function:

if (!modalOptions instanceof ModalOptions) {
    throw TypeError();
}

This introduces serious problems. Ex 1. no is longer valid. This is (annoying, but not fatal) for TypeScript consumers who do not want to create a class, but it is catastrophic for JavaScript consumers that can not implement the interface without manually wiring up the prototype chain themselves.

Another issue with linearization is that, as more interfaces are implemented, the depth of the synthetic class hierarchy grows exponentially. This becomes especially problematic in cases where interfaces extend other interfaces and classes reimplement interfaces. Consider

interface Sortable<T> {
    sort<U>(sortBy: (x: T) => U): this;
}
interface NumericallyIndexable<T> {
    [index: number]: T;
}
interface ArrayLike<T> extends Sortable<T>, NumericallyIndexable<T> {
    map<U>(projection: (x: T) => U): ArrayLike<U>;
    filter(predicate: (x: T) => boolean): ArrayLike<T>;
}
interface Grouping<K, V> {
   get(key: K): ArrayLike<V>;
}
class RichCollection implements ArrayLike<T>, Sortable<T> {
    constructor(private elements: T[] = []) { 
        elements.forEach((element, index) => {
            this[index] = element;
        });
    }
    sort<U>(sortBy: (x: T) => U) { 
        return new RichCollection(
            this.elements.sort((x, y) => x.toString().compare(y.toString())
        );
    }
    map<U>(projection: (x: T) => U) { 
        return new RichCollection(this.elements.map(projection)); 
    }
    filter(predicate: (x: T) => boolean) { 
        return new RichCollection(this.elements.filter(predicate)); 
    }
    groupBy<K>(keySelector: (x: T) => K): Grouping<K, T> { ... }
}

aluanhaddad avatar Sep 11 '16 21:09 aluanhaddad

@aluanhaddad wrote:

These statements have no place in this discussion.

Neither do these provocateurs:

It is my strong feeling that this example demonstrates the usefulness of user defined type guards.

There are no feelings involved in my objective analysis of the inability to the use the feature correctly. I would love to see someone refute my logic.

You are begging the question.

When you intentionally start a fight and promote acrimony, then don't be surprised nor offended when you get punched. Sort of logical how that works eh? Reminds of George Carlin's statement about those who in Hawaii who build their homes next to an active volcano and then are surprised when they have lava flowing through the living room.

especially after having already intimated that others are coming from an emotional place

Listen son, I don't know what your problem is, but before you make a false accusation, please remember to quote the source of your false accusation. I made no such precedent statement about others. I quoted from the FAQ. Direct any such accusation to the source.

You are making trouble. Please stay on point and leave the personal noise out of the technical discussions.

I hope this is the end of this non-technical noise that nobody wants to have to wade through. (I know it won't be the end. I know you will carry this grudge around endlessly and in the future I'll have to deal with you taking out your repressed desire to spank me. I've been on the Internet long enough to know how this works.)

shelby3 avatar Sep 11 '16 21:09 shelby3

@shelby3

Listen son, I don't know what your problem is, but before you make a false accusation, please remember to quote the source of your false accusation. I made no such precedent statement about others. I quoted from the FAQ. Direct any such accusation to the source.

In https://github.com/Microsoft/TypeScript/issues/1007#issuecomment-246127188 you wrote

Btw, are you angry? I will quote from that same FAQ:

suggesting that @kitsonk was angry. There was no evidence for that. Even if there were, you were asking the question rhetorically, which weakens your argument by introducing an ad hominem fallacy.

aluanhaddad avatar Sep 11 '16 21:09 aluanhaddad

@shelby3 You are wrong. This sort of feature is precisely what makes TypeScript different from other typed languages. While they decide NOT to trust the user unless their input fits their narrow preconceptions of what is correctly modelled code, TypeScript takes a different approach. TypeScript mostly trusts the user. The user, in turn, needs to take special care in ensuring some of their code is correct, like type guards. But not all, as it would be with dynamic languages.

This is the biggest win of TypeScript: it lets you pick between "great power, great responsibility" (carefully hand-check the code, ensure that your type assertions are correct) and "lesser power, lesser responsibility" (once you hand-"prove" type assertions are correct, you don't have to do it for the rest of the code).

Its not a type system that ensures correctness. Its a type system that works with the user to ensure it. Its a "bring your own lemma" type system.

spion avatar Sep 11 '16 21:09 spion

Its not a type system that ensures correctness. Its a type system that works with the user to ensure it does.

I agree, while acknowledging that the underlying language, JavaScript is permissive and loosely typed. Specifically quoting another TypeScript non-goal:

  1. Apply a sound or "provably correct" type system. Instead, strike a balance between correctness and productivity.

kitsonk avatar Sep 11 '16 21:09 kitsonk

@aluanhaddad:

Btw, are you angry? I will quote from that same FAQ:

Do you not see question mark? Are you just determined to ignore the difference in the English language between a question and an implication or accusation or even insinuation.

Even if there were, you were asking the question rhetorically, which weakens your argument by introducing an ad hominem fallacy.

Where is your proof that I was asking the question rhetorically? You make an assumption that I am evil because obviously that is what you want to believe (since there is no hard evidence to base your accusation). Fantasy is nice and easy. Evidence and objectivity require one to be more circumspect.

There was no evidence for that.

Perhaps you should remember to read the entire comment:

@kitsonk wrote:

why are you commenting on issues that have been closed for 18 months including picking out comments made nearly two years ago?

...

Btw, are you angry? I will quote from that same FAQ:

Anger: Don't be angry.

And the follow-up:

@kitsonk thanks for clarifying that you are not waging any political campaign against me. To clarify the way I operate, I respond and document...

Why are you wasting precious time and carrying around baggage. Let it go and focus on the technical discussion. I will not respond again on this off-topic noise.

shelby3 avatar Sep 11 '16 21:09 shelby3

@shelby3 I do not think ageist or sexists remarks have any place in a technical discussion. I felt compelled to object.

Regardless, perhaps you would care to respond to the technical side of my comment, specifically the concerns I raised about linearization of interfaces into the class hierarchy.

aluanhaddad avatar Sep 11 '16 21:09 aluanhaddad

@aluanhaddad:

In TypeScript interfaces have always been structural. ...

if (!modalOptions instanceof ModalOptions) {
    throw TypeError();
}

If the API consumes structural type, then it won't do that. If it does that, then it intends to consume nominally. The API designer hasn't lost any control. For maximum interoption with non-TypeScript transpiled consumers, the API design may choose to not to use nominal typing.

Edit: and pertaining to this thread's issue feature, if you are checking type structurally, then narrow the type using a guard via structural matching instead of nominally via instanceof or even with the property tag that this issue's feature requires.

Another issue with linearization is that, as more interfaces are implemented, the depth of the synthetic class hierarchy grows exponentially.

The entire prototype chain will only be searched for instanceof and missing properties (unless there are any Object properties needed, but this could be copied forward in the chain as an optimization). EMCAScript can choose to provide further optimizations in their standard if they realize that empty prototype objects that only exist to service the instanceof operator could be better served with a Map. And TypeScript could use a Map for optimization interim, while also populating the prototype chain for interoperability.

Inability to optimize is not usually a winning argument.


@aluanhaddad:

@shelby3 I do not think ageist or sexists remarks have any place in a technical discussion.

OMG! He pulls out the political correctness legal discrimination and State-monopoly-on-force weapon. I see you want to build a political and/or legal case for a ban or what ever. (I didn't expect it to escalate this far, so this is an eye opener for me when dealing with the latest crop of State indoctrinates)

I will have no more discussion nor interaction with you. You just earned a ban (block) from me, so will no longer see your comments. You may speak to my attorney.

Edit: unfortunately the Github block feature doesn't hide your comments from me. Nevertheless I am putting you on notice that I wish to stop all communication with you. Thank you.

shelby3 avatar Sep 11 '16 22:09 shelby3

@spion wrote:

@shelby3 You are wrong.

Wrong about what? Please quote my statement that is "wrong". Rather I think you mean to discuss and argue is your interpretation that TypeScript has design goals which don't match my concerns. That doesn't make me wrong. You know very well from other thread where you are participating, that I have stated that TypeScript's goals seem somewhat ambiguous to me.

The false accusations are flying in and now you @spion are downvoting my comments. So I see it has turned into a "shoot the messenger" politics instead of carefully thought out non-acriminous discussion of technology. That means it is digressing from technical discussion into a pissing match, and thus it is about time for me to leave unless the level of maturity and ethics rises pronto.

shelby3 avatar Sep 11 '16 22:09 shelby3

No it hasn't. You started to veer off the technical rail by discussing age and testosterone, then responded with "Let it go and focus on the technical discussion. I will not respond again on this off-topic noise". I down-voted only these two comments because they are hypocritical.

You are inconsistent, rude and abrasive. Hell, you just sliced my comment at the "you are wrong" point and proceeded to ignore the rest of it, pretending it doesn't exist, and went back to your diatribe against this feature.

I suggest you use TypeScript for at a couple of weeks before commenting further on it.

spion avatar Sep 11 '16 22:09 spion

@shelby3 I'm not going to say any more than this: from an outsider perspective, your tone is consistently aggressive. Your comments seem (to me!) to be dripping with anger. I think part of it is words like "son", which many people consider to be demeaning. Direct commands are probably another component of the perceived anger. Meanwhile, I feel like everyone else has been patiently trying to describe TypeScript's motivations, design decisions, and philosophy.

Anger and aggression in a discussion like this will convince no one.

I think you're probably right when you say that TypeScript has design goals that don't match your concerns. Maybe you could fork it and create a new language that linearizes interfaces in the way you describe? That sounds like it could be interesting, although it would be a rather different language from TypeScript, and that's OK.

mintern avatar Sep 11 '16 22:09 mintern

@spion wrote:

You started to veer off the technical rail by discussing age and testosterone

That was a response to equally abusive precedent provocateur verbiage. It helps to get your chronology correct if you want to understand who is the instigator. If you continue this political grandstanding, you will go on my block also. Stay on the technical topic, otherwise this discussion ends. (which is probably what you all are trying to accomplish any way)

Hell, you even sliced my comment at the "you are wrong" point and proceeded to ignore the rest of it, pretending it doesn't exist.

When you start with an abusive false accusation on a person what do you expect? If someone is wrong, you should be able to quote what they have written that is wrong.

I am willing to discuss the design goals of TypeScript in this thread, but you don't achieve that by saying I am wrong when I have never made any strong claim about those design goals. I have clearly communicated to you that those design goals still seem somewhat conflicting and ambiguous to me.

You are inconsistent

Another false accusation without any quote to prove this. Where have I repeatedly been inconsistent? You are fabricating an evil monster in your mind because your subconscious has decided I am the enemy of the good of TypeScript and that I refuse to understand, etc.. I know very well how this spooked packdog hindbrain works.

Oh somebody rained on your whizbang feature and has stated emphatically they think the feature is unsound and will deride TypeScript for promoting such unsoundness. And so you need to protect your tribe. Good boy. Thanks for barking loudly to warn all of us.

Fact is I have stated that I am willing to accept that if TypeScript's community and goals diverge from mine, then I have no desire to force my incongruity on them. I thought we were going to have a technical discussion, to try to illuminate if our divergence is really significant or not. But instead all this hindbrain packdog crap is making that possibility remote.

I suggest you use TypeScript for at a couple of weeks before commenting further on it.

I suggest you program for 34 years, then I'll grant you have the experience to determine whether I think I have enough relevant experience. You've gone ballistic on my person, instead of focusing on technical discussion.


@mintern wrote:

I think part of it is words like "son", which many people consider to be demeaning

I considered the continuous precedent provocateur snide verbiage accusing me of basing my comments on feelings as deserving of the response they have received.

Btw, "son" is more of a "sigh", as in "here we go again, always the same immature crap on the Internet where people would rather focus on personality than on substance and technical production".

I am not angry. I have better things to do with my time. You all are wasting time and escalating baggage.

Back on technicals exclusively or end the discussion? What is your choice kids (level of maturity/experience is evident by the lack of the ability to move on)?

your tone is consistently aggressive

Maybe you prefer feminine? My tone is matter-of-fact and masculine in the sense of stoic bluntness. I have not gone out-of-way to be disrespectful. I have offered everyone the same level of respect they show to me. And it is focused on technical discussion and trying to understand unambiguously the goals and philosophy of TypeScript.

Disagreement can alter perception.

Direct commands are probably another component of the perceived anger.

Huh? Where have I issued commands on anyone here?

Meanwhile, I feel like everyone else has been patiently trying to describe TypeScript's motivations, design decisions, and philosophy.

And I have been patiently discussing, except for the attempts to attack me starting with the first reply to me in this thread by @kitsonk that didn't discuss any technicals and instead was calling me out personally as wasting my time and effort. He then clarified that his intention was concern for me, and I thanked him for clarifying. Then @RyanCavanaugh accused me of basing my concern on "feelings" and I strongly rebuked this, because it was an afront to my desire to apply objectivity. Then @aluanhaddad went ballastic on snide comment stating I wasn't sincere about not employing my feelings. And then he piled on after I replied in kind pointing out to him that perhaps he doesn't yet have the maturity to understand how to contain his ego and tribal hindbrain, and the other packdogs have joined in the defense of the tribe. This social pattern is so common in groups, I can always see it coming. I knew right from the moment that @kitsonk posted, it had likely begun but I tried to hope "maybe not this time". But of course, it is always the same. No community will ever allow independent thought from the outside.

shelby3 avatar Sep 11 '16 22:09 shelby3

@mintern wrote:

Maybe you could fork it and create a new language that linearizes interfaces in the way you describe?

Please re-read my comments more carefully:

@shelby3 wrote:

And since interfaces have no implementation, they don't need linearization (they can be placed in the prototype chain in any random order).

shelby3 avatar Sep 11 '16 22:09 shelby3

@spoin wrote:

Its not a type system that ensures correctness. Its a type system that works with the user to ensure it.

Then afaik it is not a type system (rather some form of heuristic with probably eventual degradation into random noise). A type system by definition is:

In programming languages, a type system is a collection of rules that assign a property called type to various constructs a computer program consists of, such as variables, expressions, functions or modules.[1] The main purpose of a type system is to reduce possibilities for bugs in computer programs[2] by defining interfaces between different parts of a computer program, and _then checking that the parts have been connected in a consistent way_.

A type system associates a type with each computed value and, by examining the flow of these values, attempts to ensure or prove that no type errors can occur.

So if you introduce human error in between the declarations and the checking of their consistent interaction, then you have defeated typing.

Every value that enters the typing system has to have a correct declaration. Normally this is enforced by the compiler because it won't allow an assignment of an incompatible value to an instance of a type. But if you allow a human to tell the compiler whether a value is correct, then this enforcement is vacated.

It is possible to interopt with JavaScript's dynamically typed constructs by typing these as any in the sound type system and never allow the assignment of a value from an any to enter into the sound typing system. You could still do operations on any types knowing these operations are not sound (because they aren't even checked by the compiler), without violating the soundness of the type system.

I believe JavaScript can be typed soundly at compile-time for the portions in the compiler's type system (e.g. N4JS probably already does this), but this won't insure runtime soundness, because the compiler can't control all of the runtime. Nevetheless it will insure that the compiler's type system is internally consistent and thus reliable in that respect (at that orthogonal layer). If you violate this, then you will most likely (because of the pendulum example in chaos theory) end up eventually with a type system that is incredibly unreliable and eventually useless.

Escaping out of the type system means accepting that the compiler is no longer checking; it doesn't mean corrupting the internal consistency of the type system by introducing human error into the type system.

So okay to turn off the type system to get the flexibility you need to interopt with JavaScript in the wild, but not okay to inject into the type system unenforced types. For example, afaik in Java even casts are checked against runtime-type-information, to insure the cast doesn't violate the invariants in the type system, i.e. you can get a runtime exception with a cast. In C, you can cast an integer to a pointer and a pointer to integer, but C has no range checking on pointers any way, so no internal consistency of the type system is violated by this human error. The runtime of C for pointers is always unsound because pointer bounds are out-of-scope of the type system, i.e. the type system is turned off for pointer bounds. And unsurprisingly the largest class of bugs in C programs are pointer bugs.

shelby3 avatar Sep 11 '16 23:09 shelby3

Most languages have type systems are not 100% sound. They have various constructs which bypass or overrule the type checker. Some examples of this include covariant mutable collections, arbitrary casts (sometimes by way of intermediate casts), generic erasure, and Scalas's uncheckedVariance annotation.

TypeScript's type system is not and does not claim to be 100% sound, and it has many of the unsound constructs above, arguably for very practical reasons.

However, structural typing is not an unsoundness it is a deliberate choice which specifies the semantics of what it means to say that a value x is of a type T.

TypeScript was designed in part to formally specify JavaScript's type system. JavaScript does not have manifest type system. typeof is a type level operator but it returns a string because it cannot return a type. People generally regard instanceof as a type level operator but in fact both of its operands are always values. JavaScript is effectively a duck typed language. That it is interested in the shape and not the heritage of objects.

Structural typing allows TypeScript to model this very effectively.

aluanhaddad avatar Sep 12 '16 00:09 aluanhaddad

How many times (this is the 3rd or 4th time already) am I going to have to repeat the distinction between bypassing (i.e. turning off) the typechecker, versus introducing unchecked semantic meaning into types violating consistency of types. The salient distinction is lifting user error to the enforcement of the semantic consistency of types, not just unchecked runtime values. Turning off typing is not the same as infiltrating the types with unchecked invariants that aren't congruent with those types. Once you take values out of the type system, those values can never safely come back into the type system, except at runtime the compiler can perform a runtime verification of the invariants and throw a runtime exception on failure.

Relaxing what we expect the type system to check does not make the type system (internally) unsound.


Edit: in this issue's case, we are enabling the programmer to inject into the typing system the interface supertype of a type, removing the compiler's ability to check whether that interface supertype is valid. But this isn't just runtime behavior that is unchecked (compiler bypassed), but also the compiler's knowledge of the type has been rendered inconsistent, so that every where the compiler applies that inconsistency, it will also impact compiler checking.

And do note that even on the untyped (uni-typed) ECMAScript, the prototype chain is form of heritage of objects since it is global to all constructed instances which didn't override the prototype as constructed (and even retroactively so which is the point I want to explore modeling with typeclasses for potentially amazing benefits in productivity and extensibility).

shelby3 avatar Sep 12 '16 00:09 shelby3

@mintern wrote:

I agree, while acknowledging that the underlying language, JavaScript is permissive and loosely typed. Specifically quoting another TypeScript non-goal:

  1. Apply a sound or "provably correct" type system. Instead, strike a balance between correctness and productivity.

I interpreted that design goal to mean that the type system wouldn't check everything and that absolute runtime (external) soundness isn't a realistic goal for the full range of the JavaScript universe (libraries, frameworks, etc) as it is today. And I agree.

I did not interpret it to mean that we should purposefully inject unenforced types into the type system to destroy the internal consistency soundness of the type system, potentially turning it into random soup of contagion of the chaotic interaction of multiple heuristics in an eventual exponential explosion of Complexity of Whoops, i.e. loss of productivity.

Again I find the design goals document to be somewhat ambiguous and/or self-conflicted. I don't know what the purpose of building a type system with internal inconsistency would be. I guess some sort of hit-and-miss hint system, hoping it provides more hits than misses over time. Do we have the long-term track record of any prior examples to compare to? Again afaics comparing to turning off (i.e. escaping out of, bypassing) the type system is not analogous.

shelby3 avatar Sep 12 '16 00:09 shelby3

@shelby3 wrote:

The salient distinction is lifting user error to the enforcement of the semantic consistency of types, not just unchecked runtime values.

Thinking about if the feature enabled by this issue is not first-class, and thus unable to infiltrate the rest of the type system, thus cordoning the impact of any human error. It appears to not be first-class, except perhaps for example maybe the narrowed type can be used along with partial function application (does TypeScript have partial function application?) to select which of an overloaded function (or method) is saved to a callback instance, which is then passed around as a first-class function which can leak into any part of the type system.

Also thinking about @aluanhaddad's point that when interopting with JavaScript that didn't populate the prototype chain with interfaces per my alternative suggestion for a compiler-assisted and enforced check, it would be perhaps less globally conflated to set a member property per the feature of this issue versus setting up the global prototype chain of a constructor function. Yet wouldn't the TypeScript code which depends on this instanceof be forced to import the module for the declaration of the type it is employing, thus wouldn't the prototype chain be guaranteed to exist in the global scope? I mean if at runtime, the caller can violate the expected type, then caller can violate List and BaseCollection also, not just the interfaces which TypeScript doesn't currently add to the prototype chain.

So again I arrive at the same conclusion, which is that if we want to use TypeScript typing, then we have no guarantees about runtime soundness any way, unless we can assume TypeScript has been employed globally in your ECMAScript universe. So I see no benefit to destroying the soundness of the internal consistency of the TypeScript type system. If the caller isn't interopting with the TypeScript type system where the callee is depending on it, then there will be runtime errors. Enabling some heuristic convenience user-guard so that callers which don't want to set the prototype chain can instead set some member property on the specific instance, is moving us towards utter chaos if such heuristics proliterate. Where do you draw a line and stop creating special case interactions which render the type system inconsistent?

One can I guess argue that since the JavaScript universe outside of TypeScript does not have prototype interfaces (unless setting the prototype chain with interfaces becomes a common programming paradigm), then the adhoc paradigm employed in practice has been to set a member property on an instance to tag it as having a certain interface and thus TypeScript should emulate this form of user-defined, adhoc, inconsistent (compiler unchecked) "typing", so as to interopt with this paradigm, i.e. sacrificing correctness for an increase in interopt productivity. Yet OTOH, we have to opportunity to influence the JavaScript universe to start using the prototype chain for what it is capable of, and keep the TypeState typing system internally consistent, which in another perspective is a greater advance of productivity by not ending up over time with a typing system that is spaghetti contagion of Complexity of Whoops random noise rendering the type system useless.

Edit: in this issue's case, we are enabling the programmer to inject into the typing system the interface supertype of a type, removing the compiler's ability to check whether that interface supertype is valid. But this isn't just runtime behavior that is unchecked (compiler bypassed), but also the compiler's knowledge of the type has been rendered inconsistent, so that every where the compiler applies that inconsistency, it will also impact compiler checking.

I am all for easing interoption with the untyped JavaScript universe when it doesn't render the internal type system inconsistent. In my analysis it is okay to forsake runtime soundness, because the only way we will get very strong runtime soundness is to have the type system every where, i.e. perhaps Google's SoundScript in the VM in the remote future (i.e. a different language than what ECMAScript is now). But I am not seeing how corrupting the type system will lead to long-term stable productivity increase (the type system can potentially become so brittle and inconsistent over time into a clusterfuck). I am making a distinction between bypassing the type system for unchecked runtime behavior and injecting inconsistency into the type system itself. Is that distinction a mirage? I mean is there no way to bypass the type system when needed, which doesn't also impact the internal consistency of the type system? Am I only appealing to subjective religion?

shelby3 avatar Sep 12 '16 05:09 shelby3

I offered an idea about populating the prototype chain with interfaces as a more JavaScript idiomatic paradigm (seems that is the purpose of prototype, thus the idiomatic place to tag the interface structure) and which doesn't break the internal consistency of the TypeScript type system, as an alternative to this issue's adhoc choice of setting member properties on specific instances without any enforcement by JavaScript's prototyped instance construction mechanism, thus breaking the internal consistency of TypeScript while also being non-idiomatic for non-TypeScript code. For me, that already appears to be a slamdunk "no brainer".

There is potentially another way to do this though. That is for the compiler to make a new type check (not instanceof which relies on the prototype chain) which has the semantics of checking what the compiler knows which may be erased at runtime. And employ this new feature (keyword?) to do guards. The JavaScript runtime would be completely oblivious to this erased information and the non-TypeScript code wouldn't be able perform these checks at runtime, but it also wouldn't need to interopt on the requirements for the prototype chain.

And there is yet another way, which I am surprised that no one offered instead of this issue's feature:

@shelby3 wrote:

Edit: and pertaining to this thread's issue feature, if you are checking type structurally, then narrow the type using a guard via structural matching instead of nominally via instanceof or even with the property tag that this issue's feature requires.

If interfaces are intended to be purely structural, then there is no need to tag with a property and add an _ is Type feature (for the purpose of narrowing of type at the guard). Simply match on structure at the guard instead (and use the result of the match to narrow the type). So you'd need some new compiler provided function that performs this structural match similar to my second paragraph in this comment. And at compile-time, this function need not be called because the compiler can infer the type. At run-time, the function would actually need to be called to do a structural matching to check for the interface type .


Meanwhile, I feel like everyone else has been patiently trying to describe TypeScript's motivations, design decisions, and philosophy.

And I have been patiently discussing, except for the attempts to attack me starting with the first reply to me in this thread by @kitsonk that didn't discuss any technicals and instead was calling me out personally as wasting my time and effort. He then clarified that his intention was concern for me, and I thanked him for clarifying. Then @RyanCavanaugh accused me of basing my concern on "feelings" and I strongly rebuked this, because it was an afront to my desire to apply objectivity. Then @aluanhaddad went ballastic on snide comment stating I wasn't sincere about not employing my feelings. And then he piled on after I replied in kind pointing out to him that perhaps he doesn't yet have the maturity to understand how to contain his ego and tribal hindbrain, and the other packdogs have joined in the defense of the tribe. This social pattern is so common in groups, I can always see it coming. I knew right from the moment that @kitsonk posted, it had likely begun but I tried to hope "maybe not this time". But of course, it is always the same. No community will ever allow independent thought from the outside.

P.S. note the lack of exhaustive discussion of alternatives before this issue's _ is Type feature was chosen and merged, indicates to me a dearth of sufficient diverse participants in this community. Please do not chase away dissenting technical opinions. You need them. Consider the value of learning to be tolerant of others and value their technical disagreement. Greatness requires it.

shelby3 avatar Sep 12 '16 07:09 shelby3

Please do not chase away dissenting technical opinions. You need them. Consider the value of learning to be tolerant of others and value their technical disagreement. Greatness requires it.

I couldn't agree more. However, it's perfectly valid to program with functions and object literals and to never use classes or even manually wired inheritance via prototypes.

Simply match on structure at the guard instead (and use the result of the match to narrow the type). So you'd need some new compiler provided function that performs this structural match similar to my second paragraph in this comment. And at compile-time, this function need not be called because the compiler can infer the type. At run-time, the function would actually need to be called to do a structural matching to check for the interface type .

What specifically do you have in mind? Type guards are most often used when type information has been lost because it comes from untyped APIs and unknown sources. If the compiler could always determine the actual type, we wouldn't be having this discussion but that is simply not possible.

And do note that even on the untyped (uni-typed) ECMAScript, the prototype chain is form of heritage of objects since it is global to all constructed instances which didn't override the prototype as constructed (and even retroactively so which is the point I want to explore modeling with typeclasses for potentially amazing benefits in productivity and extensibility).

I would definitely be curious to see your formal type class proposal. I think it is a very interesting point that you bring up here about retroactive modification of the prototype chain. Since the prototype property of an object and the prototype's properties are in fact frequently mutable, an object can change at any point during execution such that it no longer matches it's declared static shape. Furthermore, irrespective of mutability, you can create an object which will pass the check o instanceof Date, but not conform to Date's behavior. This is because JavaScript's instanceof operator has no notion of types it only understands values. Walking the prototype chain and doing reference comparisons is far from reliable.

I think that as you have yourself stated, a different language, one targeting a type aware VM may well be the only way to achieve your goals.

That said, you really should spend some more time with the language and see if it is in fact useful to you before continuing. One important thing to be aware of is that TypeScript's classes are structurally typed not normally typed. This is a structurally typed language.

aluanhaddad avatar Sep 12 '16 08:09 aluanhaddad