text:
is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes

TypeScript Version:  2.3.1
Code
With the above mentioned version I can't spread Props objects anymore to child React components, when the Props don't match up 100%.

/* App.tsx */

interface Props {
    ...
    scopes: any;
}

interface State {}

export class App extends React.Component<Props, State> {
    render() {
         return <Content {...this.props} />; // error
    }
}

/* Content.tsx */

interface Props {
    ...
    // without scopes in Props
}

export default class Content extends React.Component<Props, {}>{
    ...
}

Expected behavior:
No error and there wasn't any on 2.2.1
Actual behavior:
error:
ERROR in ./spa/js/comps/App.tsx
(121,49): error TS2322: Type '{ ui?: UIState; session?: SessionState; scopes?: any; users?: any; roles?: any; plugins?: any; us...' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Content> & Props & { children?: ReactNode; }'.
  Property 'scopes' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Content> & Props & { children?: ReactNode; }'.

You can do like below, but may get a warning about scopes being unused.
export class App extends React.Component<Props, State> {
    render() {
         const { scopes, ...otherProps } = this.props;
         return <Content {...otherProps} />;
    }
}

The same question. It's hard to understand why the following code will not compile anymore in v2.3
import * as React from "react";

interface ComponentProps {
    property1: string;
    property2: number;
}

export default function Component(props: ComponentProps) {
    return (
        <AnotherComponent {...props} />
    );
}

interface AnotherComponentProps {
    property1: string;
}

function AnotherComponent({ property1 }: AnotherComponentProps) {
    return (
        {property1}
    );
}

due to the error
Type '{ property1: string; property2: number; }' is not assignable to type 'IntrinsicAttributes & AnotherComponentProps'.
  Property 'property2' does not exist on type 'IntrinsicAttributes & AnotherComponentProps'.

A little bit different but still the same.
export default class Panel extends React.Component<void, void> { ... }
leads to this error
TS2322: Type '{}' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Panel> & Readonly<{ children?: ReactN...'.    Type '{}' is not assignable to type 'void'.
Had to change void to any, null or undefined to make it work.

@luca-moser @luggage66 @etecture-plaube @pomadin  The reason for change in behavior is that in 2.3, JSXAttributes are type-check similar to object literal expression with freshness flag (this means that excess properties are not allowed) After discussing with @mhegazy, it is too restrictive and cases in examples here illustrate that. So we will make modification to the rule as follow:

If there exist JSX attributes that are specified explicitly such as
 or
, attributes objects will get freshness flag and undergo excess properties hceck

If there are only spread in JSX attributes such as
 excess properties will be allowed

I will get the PR up today and the fix should be in for tomorrow nightly if you would like to give that a try!

@yuit If you only allow the second case in your list, it will still break a lot of components. Often, parent components spread their Props object further and compute some additional things which are passed explicitly.
Here's an example from my actual codebase:
this.props.users.sort((a, b) => a.name > b.name ? 1 : -1).forEach((user: User) => {
    if (user._filtered) return;
    users.push(<UserCard {...this.props} key={user.id} user={user}/>);
});

@luca-moser Thanks for feed back! Here is the second thought :

Only contain explicitly attributes -> no excess properties allowed
Contain spread attributes (even with explicit attributes) -> 1. check type assignability (allow access properties) 2. for each explicit attributes check if the attribute name match the target name.

I agreed with @luca-moser, it's common case to extend the props or to override some ones.
@yuit, the final solution looks acceptable as the 1st case (only explicitly attrs...) fits no jsx case.
interface Props {
    p1: string;
}

function fn(props: Props) {
}

fn({ p1: "", p2: 1 }); // ERROR: Object literal may only specify known properties...

I also have a lot of Spread types may only be created from object types. for { ...this.props } in cases that worked well in 2.2.2,
For case <Container  somePropery={this.privateMethod} /> I get 'privateMethod' is declared but never used.. If I pass the property like <Container  { ...{someProperty: this.privateMethod}} /> or make method public, the error is gone

@IIIristraM could you share more repo for both cases. the Second may get fixed in the nightly. IF you could share a full repo, I can take a look

import { inject, observer } from 'mobx-react';
import * as React from 'react';
import { ProviderContext } from 'types';

interface IMapFunction<TInnerProps, TOuterProps> {
  (context: ProviderContext, nextProps?: TOuterProps): TInnerProps;
}

export default <TInnerProps, TOuterProps>(mapStore: IMapFunction<TInnerProps, TOuterProps>) => (
  (Component: React.ComponentClass<TInnerProps>) => {
    const Observer = observer(Component);

    @inject(mapStore)
    class Connector extends React.Component<TInnerProps & TOuterProps, {}> {
      public node: React.Component<TInnerProps, any>;

      private setNode = (n: React.Component<TInnerProps, any>) => {
        this.node = n;
      }

      public render() {
        return <Observer { ...this.props } ref={this.setNode} />;
      }
    }

    return Connector as React.ComponentClass<TOuterProps>;
  }
);

Where  an error occur? Is it at here return <Observer { ...this.props } ref={this.setNode} />; ? can you share that class declaration if that is the case.

Yes, this is right code line.
Component can be an any React component,  observer(Component) returns typeof Component

@luca-moser Thanks! I am able to see this error Spread types may only be created from object types...this is consistent with how the spread type work in our system at the moment.  Though I am talking with @sandersn @mhegazy later to see what we can do about that

@luca-moser @luggage66 @pomadin  @etecture-plaube  @IIIristraM  We have fix for original in the master. It should be out for nightly tonight. Give that a try and let us know.  We will have this fix for 2.3.3 as well.
@IIIristraM  Note: the fix doesn't address " Spread types may only be created from object types" I will get that in another PR

@yuit I have compiled my code via build 2.4.0-dev.20170509, the error is gone. So I am waiting for v2.3.3 to move on.

@pomadin  thanks for the feedbacks. We will have this fix in for 2.3.3

Installing typescript@next (2.3.9-dev..) has solved my issue.

export function makeP
(Ctor: React.ComponentClass
): React.ComponentClass
 {
    return class extends React.PureComponent
 {
        public static displayName: string = 'name';
        public render(): JSX.Element {
            return (
                <Ctor {...this.props }/>
            );
        }
    };
}

@yuit for 2.3.3-insiders.20170512 it still does not work (and for 2.4.0-dev.20170515 too).
export class Test extends React.PureComponent<void, void> {}
export const a = <Test/>;

fails with error TS2322: Type '{}' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Test> & Readonly<{ children?: ReactNode; }> & void'. Type '{}' is not assignable to type 'void'.

@yuit please take a look

third time is a charm :). Please give typescript@next tomorrow 5/16.

@mhegazy it works, thank! Is there a chance to have this fix in 2.3.3 (or next patch of 2.3)?

it should be in TS 2.3.3 later this week.

Having a similar issue @ Typescript 2.3.4
Type '{}' is not assignable to type 'Readonly<ISpinnerProps>'. Property 'showGlobalSpinner' is missing in type '{}
Component 1:
interface ISpinnerProps{
    showGlobalSpinner: boolean
}
export class Spinner extends React.Component<ISpinnerProps, undefined> {
    render() {
         return (
         // Some markup
         )
    }
}

Component 2:
interface IProps {
   someOtherProp: string
}
export class App extends React.Component<IProps, undefined> {
    render() {
         return (
         // Some markup
         <Spinner/> // Error is thrown here.
         )
    }
}

This pattern to used to compile fine earlier.

showGlobalSpinner is a required property of Spinner. either set the property, or declare it as optional in ISpinnerProps.

@mhegazy  The problem is this showGlobalSpinner prop is passed down by Redux connect. I think TS thinks that I'm handling passing these props via parent.

I have the same problem as @levsthings, @mhegazy - the connect() method return type now seems to now require the props are set in the TSX when consuming the redux-connected component, whereas they are actually provided by react-redux. If anyone is able to decipher the issue with the typings please let me know! Heres a link...
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-redux/index.d.ts

This seems to be the breaking commit: https://github.com/DefinitelyTyped/DefinitelyTyped/commit/2bc7feeb48e5c79fac1d4a09b36b5ce8c80896af
Works in types/react-redux@4.4.40 and not in types/react-redux@4.4.41

@giladaya You're correct, I've also confirmed that the entire problem stems from types/react-redux@4.4.41.

@dupski @giladaya @levsthings Can you comment on the PR. I think that's a better place for it than this issue since it's a different cause.

@levsthings this is also an issue when using mobx inject. Anyone have any insight on how to properly do this elegantly?

export function Stateless
 (Component: typeof React.Component): React.StatelessComponent
 {
  const StateLessComponent: React.StatelessComponent
 = props => (
    <Component {...props}>
      {props.children}
    </Component>
  )

  return StateLessComponent
}

const CCol = Stateless<IColProps>(Col)

My editor not showing the error. But the compiler shows the error

app: (38,20): error TS2339: Property 'md' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<{ theme?: any; innerRef?: ((instance: an...'.

Hi @pomadin , I met the same problem and then found the reason that is
you SHOULD pass value for those parameter in use.
For example:
<Component property1={'parents'} property2={'kids'} />
If you delete "property1={'parents'} property2={'kids'}" the TS will notify error

I had the same issue which I resolved by extending  JSX.IntrinsicAttributes adding a data field to it:
interface JSXData<T> extends JSX.IntrinsicAttributes {
  data : T;
}

const Row = (props: JSXData<BalanceEntry>) : JSX.Element => {
  return (

        {props.data.name}

        {props.data.nett}

        {props.data.tax}

  );
}

class BalanceEntry {
  name: string;
...
  nett: number;
  tax: number;
}

so I could render the table as follows:

 render() {
    let rows = this.data.map(entry => {
      return <Row
          key={entry.id}
          data={entry}
        />
    });

    return (

          Entry
          Nett
          Tax

{rows}

    );
  }

Started using v 2.6.1 today and can still see a lot of errors similar to ones discussed here, i.e.
import * as React from "react";
import styled from "styled-components/native";
import { TouchableOpacity } from "react-native";

// -- types ----------------------------------------------------------------- //
export interface Props {
  onPress: any;
  src: any;
  width: string;
  height: string;
}

// -- styling --------------------------------------------------------------- //
const Icon = styled.Image`
  width: ${(p: Props) => p.width};
  height: ${(p: Props) => p.height};
`;

class TouchableIcon extends React.Component<Props> {
  // -- default props ------------------------------------------------------- //
  static defaultProps: Partial<Props> = {
    src: null,
    width: "20px",
    height: "20px"
  };

  // -- render -------------------------------------------------------------- //
  render() {
    const { onPress, src, width, height, ...props } = this.props;
    return (
      <TouchableOpacity onPress={onPress} {...props}>
        <Icon source={src} width={width} height={height} /> /* errors */
      </TouchableOpacity>
    );
  }
}

export default TouchableIcon;

/* errors /* -> i not assignable to type IntrinsincAttributes ...
this happens for all: src width an height

Started using v 2.6.1 today and can still see a lot of errors similar to ones discussed here, i.e.

I am not familiar with styled-components, but seems like you have Props requiring src and onPress. and that is the err you are getting.. the error is not about src, width and height, it is about missing properties.

I just added react-router-dom to a https://github.com/wmonk/create-react-app-typescript app and added the following code and got a similar error:

any ideas?

@QuantumInformation use RouteComponentProps from 'react-router' in your Home component
export class Home extends React.Component<RouteComponentProps<void>, any>

I'm using ConnectedRouter now and it just works, even with just:
const Home = () => (

Home

)

I'm also having issues with this
interface RoleProps {
  radius?: number;
  size?: "small" | "medium" | "big";
  look?: "primary" | "secondary" | "dark" | "light";
}

export class Button extends React.PureComponent<RoleProps> {
  render() {
    return (
      <InternalButton  {...this.props} > {this.props.children} </InternalButton>
    )
  }
}

// InternalButton has P = <RoleProps & Themer>

 error TS2322: Type '{ children: ReactNode[]; radius?: number | undefined; size?: "big" | "small" | "medium" | undefin...' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<Pick<RoleProps & Themer, "radius" | "siz...'.
  Type '{ children: ReactNode[]; radius?: number | undefined; size?: "big" | "small" | "medium" | undefin...' is not assignable to type 'Readonly<Pick<RoleProps & Themer, "radius" | "size" | "look"> & HTMLProps<HTMLButtonElement> & Ex...'.
    Types of property 'size' are incompatible.
      Type '"big" | "small" | "medium" | undefined' is not assignable to type '(undefined & number) | ("big" & undefined) | ("big" & number) | ("small" & undefined) | ("small" ...'.
        Type '"big"' is not assignable to type '(undefined & number) | ("big" & undefined) | ("big" & number) | ("small" & undefined) | ("small" ...'.

That should technically work as the common props should spread.

Hey guys I got the same problem too,please help me
<Button label="Force Update" onClick={() => {
          // this.setState({splits});
          setInterval(() => {
            let width = this.state.width - 10;
            this.setState({width});
          }, 100);

        }}></Button>

 Type '{ label: "Force Update"; onClick: () => void; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Button> & Readonly<{children?: ReactNode; }> & Re...'.
  Type '{ label: "Force Update"; onClick: () => void; }' is not assignable to type 'Readonly<{ icon: Element; label?: string; title?: string; isDisabled?: boolean; onClick?: Functio...'.
    Property 'icon' is missing in type '{ label: "Force Update"; onClick: () => void; }'.

ERROR in [at-loader] ./src/util.ts:81:19

@ILL35T NavScroller extends React.Component<SportProps> so when rendering it you need to pass SportProps as its props, but you are not passing it any props and that is the reason for the error. If the props are optional then they need to be marked as such with ? or if you want to make them all optional then maybe extend React.Component<Partial<SportProps>>
@nileshgulia1 Property 'icon' is missing in type '{ label: "Force Update"; onClick: () => void; }' you need to either pass Button an 'icon' prop or mark it as optional on the ButtonProps interface.

@sandersn Sorry to get back to you so late.
I made it simple for testing, it's just
export interface Themer {
    theme: { color: string }
}

What I am trying to figure out that is ambiguous and unclear (a failure I attribute to TypeScript or at least its documentation) is out the spread operator works overall.
Perhaps you could help clear that up here, and we could take a look at the documentation to make it less ambiguous.
https://github.com/Microsoft/TypeScript/issues/15463#issuecomment-353257033

I am having same issue but only when I saperate out component and containers!

Yes, I too am having the issue. If you pull in a container that gets its properties from a redux store, you cannot compile without specifying the properties

I'm also having this exact same issue and I've spent the better part of the day scouring the internet trying to find what's wrong since this issue doesn't have an update. I've tried following different tutorials on different ways to connect redux with react.
For the ~16 hours I've spent today on this I'm coming to the conclusion that React + Redux + TS doesn't work.
Typescript: 2.7.2
Sample:
(10,16): Property 'createBook' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'.

With this simple:
import React from 'react';
import { connect } from 'react-redux';

class Book extends React.Component {
  constructor(props: any){
    super(props);
  }

  submitBook(input: any){
    this.props.createBook(input);
  }

  render(){
    let titleInput;
    return(

Books

          {this.props.books.map((b, i) =>
{b.title}
 )}

Books Form

          <form onSubmit={e => {
            e.preventDefault();
            var input = {title: titleInput.value};
            this.submitBook(input);
            e.target.reset();
          }}>
            <input type="text" name="title" ref={node => titleInput = node}/>
            <input type="submit" />
          </form>

    )
  }
}

// Maps state from store to props
const mapStateToProps = (state, ownProps) => {
  return {
    // You can now say this.props.books
    books: state.books
  }
};

// Maps actions to props
const mapDispatchToProps = (dispatch) => {
  return {
  // You can now say this.props.createBook
    createBook: book => dispatch({
      type: 'ADD_BOOK',
      id: book.id
    })
  }
};

// Use connect to put them together
export default connect(mapStateToProps, mapDispatchToProps)(Book);

@mechanic22 It's not perfect, but I just did return React.createElement(MyList); to solve this.

@tsteuwer you should let Book to know that would be it's props. that connected components will be exported, so not-connected raw Book component don't know it's type of Props
so if you do this
interface IBook {}
interface Props {
  books: IBook[],
  createBook: (book: IBook) => void
}
class Book extends React.Component<Props> {
  ...
}

then it will be ok

@levsthings I got the same issue, but I don't see any solution apart from what @PaitoAnderson suggested (return React.createElement(MyList); -- that worked). So what about a proper way?

This issue is the reason I'm choosing Flow for my next project.

authors: DeDuckProject FourwingsY IIIristraM IljaDaderko PaitoAnderson Peterabsolon QuantumInformation RyanCavanaugh activebiz andrerpena dupski etecture-plaube frankwallis giladaya iKBAHT kidqn levsthings luca-moser luggage66 mechanic22 mhegazy nileshgulia1 nuviosoftware pomadin rohmanhm sakalys sandersn seivan timocov tsteuwer yuit


text:
Imported type overrides local value declaration, yielding undefined

TypeScript Version:  2.3.3, nightly (2.4.0-dev.20170525)
Code
// Main.ts:
import { X } from './Types'
const X = 42;
console.log('X is ' + X);

// Types.ts:
export type X = {}

Expected behavior:
Output: X is 42
Actual behavior:
Output: X is undefined
The value reference X is transpiled to the undefined Types_1.X instead of just X. Declaring type X = {} in Main.ts instead of importing it works correctly.

Much appreciated!

source: gharchive/issue

repo: Microsoft/TypeScript

license_type: permissive

license_source: github-api


text:
Performance issue with union of string literal types

TypeScript Version:  2.5.2
I've been experiencing a significant sudden slowdown in my build time for a while, and I've finally isolated the cause to a short block of code which hopefully will reproduce the issue.
The following code file takes me about 10-15 seconds to compile:
Code
import * as React from 'react';
import styled, { StyledComponentClass } from 'styled-components';

export type IButtonProps = React.HTMLProps<HTMLButtonElement> & {
    mode?: 'primary' | 'secondary';
};

export const Button = styled(({ mode, ...rest }: IButtonProps) => (
    <button {...rest} />
))``;

export const PrimaryButton = styled(Button).attrs({ mode: 'primary' })`
`;

(No special tsconfig, just defaults + "jsx": "react". No special dependencies just @types/react and styled-components.)
It seems to be something to do with the line:
mode?: 'primary' | 'secondary'

As if I change the type of this to just string, it builds in about 1 second.
Hopefully this can be reproduced but it seems an odd one. If this is somehow local to me, is there any way I can self-diagnose performance issues with the compiler? (e.g. logging)
EDIT: I've just tried with typescript@next, and I don't get the same issue..?
EDIT 2: I should also add that it slows down the language service too; VS (and presumably others) fail to do intellisense, and my CPU usage goes through the roof.

EDIT: I've just tried with typescript@next, and I don't get the same issue..?

We have made  a lot of perf/memory fixes over the past few weeks. these changes are in master (typescript@next) and were not in 2.5.2.
Can you give typescript@insiders a try and let us know if it does address the perf issues?

Yes, the 2.6 dev version doesn't appear to have this problem! Thanks!

can you also give typescript@2.5.3-insiders.20170922 a test? this is what we intend to ship as @2.5.3 next week.

authors: jamiewinder mhegazy


text:
LanguageService : getCompletionsAtPosition returning 0 results for a few cases

Specifically the following two cases:
function w(x: { test: string }) { return ''; }
// Press Ctrl + space below
w({ /*before here*/ });
// Press Ctrl + space below
w({test:''})./*before here*/

refs : https://github.com/TypeStrong/atom-typescript/issues/82

Nevermind. My bad. :heart:


text:
Salsa - Missing Intellisense and error with ts-check when 'express' packgage is installed but not used.

Vs Code Version: 1.19.1
Tested on Linux and Windows.
I created simple folder with index.js and jconfig.json file:
index.js
const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

jsonconfig.json
{
    "compilerOptions": {
        "target": "ES6",
        "module": "commonjs",
        "jsx": "preserve"
    },
    "exclude": [
        "node_modules",
        "**/node_modules/*"
    ]
}

Intellisense works here for imported modules:

But when I install express library (by npm install express -s), the typeof imported module is any

now when I add // @ts-check i get error

But it works again when I import "express"

This was very confusing that I lost Intellisense (and got errors when used checkJs:true in jsconfig.json) just by simply installing package.

Should be covered by the proposal in https://github.com/Microsoft/TypeScript/issues/21933.

authors: mhegazy mpawelski


text:
Formatting of conditional types

TypeScript Version:  2.7.0-dev.20180206
Expected behavior:
type Diff<T, U> = T extends U ? never : T;

Actual behavior:
type Diff<T, U> = T extends U?never: T;

Related Issues:

@lankaapura wanna pick up this one as well?

@mhegazy sure 👍

Created PR #21762, let me know if there any changes required.

authors: falsandtru lankaapura mhegazy


text:
Watch mode doesn't correctly invalidate failed subdirectory lookup results

TypeScript Version:  2.8.0-dev.20180318
Search Terms: watch mode subdirectory
Code
You'll need 4 files
// tsconfig.json
// FOR THIS BUG, ORDER MATTERS IN THE FILE ARRAY
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs"
  },
  "files": [
    "foo/a.ts",
    "foo/bar/b.ts"
  ]
}

// foo/a.ts
import * as q from 'qqq';

// foo/bar/b.ts
import * as q from 'qqq';

// node_modules/qqq/index_.d.ts
export { }

Run tsc -w:
20:37:52 - Starting compilation in watch mode...
foo/a.ts(1,20): error TS2307: Cannot find module 'qqq'.
foo/bar/b.ts(1,20): error TS2307: Cannot find module 'qqq'.
20:37:54 - Compilation complete. Watching for file changes.

Rename index_.d.ts to index.d.ts:
20:38:26 - File change detected. Starting incremental compilation...
foo/bar/b.ts(1,20): error TS2307: Cannot find module 'qqq'.
20:38:26 - Compilation complete. Watching for file changes.

Expected behavior: In the second compilation, b.ts should be able to correctly resolve qqq.
Actual behavior: Failure as shown above. Reversing the order of files in the files array produces the expected behavior.
Playground Link: N/A
Related Issues: None?

The issue here is that when we do the lookup for qqq from foo/, we store the result that a lookup is known to fail. We track the list of failed lookup locations produced from this.
During the lookup of qqq from foo/bar/, we produce a smaller set of failed lookup locations, then go up a folder and see that we've already tried to resolve that module from that location, so we cut the search short. But we don't concatenate the list of failed lookup locations that the earlier search generated.
As a result, when node_modules/qqq/index.d.ts appears, we correctly identify that a.ts needs to have module resolution redone, but b.ts is still only waiting for foo/bar/node_modules/qqq to show up.
When this process happens in the other order, foo/ can't re-use the lookup results from foo/bar/ and the bug does not manifest.
Fix in progress is to store the failed lookup locations in the cache along with the lookup result.


text:
Greatly improve code sharing and reuse options

Creating and sharing pure typescript code has quite a few barriers that seem like the kind of complexity that TypeScript should be helping to alleviate.
I'm going through a situation right now where I want to share a pure typescript library and - unless I'm mistaken - it seems like I'm going to have to go through the pain of adding AMD to my project.  Even despite the fact that it's all internal modules.
With the overall goal of making life easier for developers, I think it would be nice if:

There was some way to reference typescript files statically such that they are used in the compile process.  This could even be used to eliminate the /// syntax used to load .d.ts files.
There was some way to tell typescript to prepend regular javascript files to the entire build output (dependencies with .d.ts definitions for example).

While AMD/CommonJS are module-loading systems, they are very confusing and cluttered build systems, especially once you bring TypeScript into the mix.
It's conceivable that with these changes, you'd also reap the ability to create build profiles implicitly by defining entrypoint scripts and having typescript crawl the dependency graph.  Similar to how r.js works, except at a TypeScript level.

It should probably be mentioned that any solution really needs to be sensitive to the possibility that the node_modules and typescript sources directories that the compiler is currently targeting will not be consistent between projects.
This might be one of the major pain points of coming up with a build system that knows how to integrate code from packages.

For your first bullet, is tsconfig not a solution to the problem you're experiencing?
For the second bullet, this is something we've generally stayed out of. People have very varied build systems with a variety of linters, concatentation steps, minifiers, etc and it seems difficult for us to cover the majority of those scenarios in a satisfactory way (and convince someone to break their existing, working system to migrate to the provided TS one). Maybe the solution is to make it easier to customize pre and post build steps. We generally don't want to be in the business of creating some robust, general purpose, cross platform build system. Obviously it's important that the end to end experience be as good as possible though, so maybe we need to make changes to slot into existing workflows more easily or be better at detecting errors that might have occurred as a result of that system.
For node_modules #247 is a priority and hopefully helps alleviate some of the mismatch with using TS + npm modules now. Could you elaborate on what you mean by node_modules and TS sources not being consistent beyond that?

I know I can't speak for others, but I think a build system integrated with typescript would be a welcome change to getting mired in endless build system hacking and configuration.
In an ideal world, I should be able to do this:
tsc path/to/built.js path/to/script.ts
BUT
TS has a way of resolving and including in the build everything that script.ts references.
What's preventing this from being a possibility?

I think a build system integrated with typescript would be a welcome change to getting mired in endless build system hacking and configuration.
Sure, but this is really a complaint about the state of JS build systems and wishing for a great 'one build system to rule them all.' In an ideal world that would exist :) In reality peoples' needs are extremely varied which is why we have many different options (many tried to create the one true build system, now we just have a lot of different ones with different pros and cons). We don't feel like we're in any better situation to suddenly solve that problem better than all the other attempts (especially prior to ES6 having a finalized, cohesive module story). And then there's the fact that even if we actually did succeed at that, many people are not going to switch from their working build system to something new, even if the new thing is better in the abstract ('if it ain't broke...'). That said, we do want to try to slot into what exists well, and we do want to enable others to make good tools around us (like interacting with grunt/gulp/etc).
What's preventing this from being a possibility?
What do you mean by 'everything that script.ts references'? You mean a file without /// or imports? Or a file with ES6 style imports? Obviously right now the compiler does chase through your /// references and imports or will use a tsconfig related to that script. It sounds like you mostly want to avoid /// reference pain which is what tsconfig should help with.

So for tsconfig, I have to manually create one for every graph of source files I want to use?  Why not just have the compiler automatically infer this?  r.js does this when you tell it to build a file.  It will recurse through all the imports and concatenate all those files together.
If I was able to statically reference other .ts files from one root-level .ts script, wouldn't that obivate the need for various mechanisms to tell the compiler about where files are?  The compiler would know everything being used because it would have crawled the full import-graph (my root script, it's dependencies, their dependencies, and so on) before going through the code.

So for tsconfig, I have to manually create one for every graph of source files I want to use?
Not for every graph necessarily, it's up to you whether you want to explicitly list everything or let reference chasing happen depending on what references are in relevant files. Think of it like a basic project file.
Why not just have the compiler automatically infer this? r.js does this when you tell it to build a file. It will recurse through all the defines and requires and concatenate all those files together.
This is exactly what the compiler currently does with .ts files based on the /// references and import/require in the file. With RequireJS you explicitly list your module's dependencies, and each dependency has its own dependency list, and the loader walks through this graph. That's the same thing tsc does when you explicitly list dependencies in the form of /// or import/require. The problem is that explicitly managing /// references in this way can be painful and sometimes things get pulled in in an unexpected order and now you have to manually try to track down how the graph was traversed and what happened. Using a tsconfig to manage the project ordering can alleviate some of this pain.

So general advice for the time being is that I should be making everything external and not really try to make internal modules?  That's a distinction I'm still trying to internalize, but I was under the impression that there might be a way for me to do all this without having to set up AMD....

It's really up to you as far as how you want people to consume your code. Given that ES6 only has external modules it's certainly possible that's the right choice for you going forward though. The TypeScript compiler is only internal modules but you can find small npm packages that provide access to it through external modules. Likewise you'll see some .d.ts files written in such a way as to work with both internal and external (I believe knockout is one example like this).

I'm still at a loss to really understand what the difference is between internal and external.  Some of it flies over my head.

I assume you've read https://github.com/Microsoft/TypeScript/wiki/Modules and http://www.typescriptlang.org/Handbook#modules ? Don't feel bad, it is unfortunately confusing and a situation we definitely can improve. I'm reticent to try to give an off the cuff primer since we've already spent a bunch of time trying to wordsmith the content in those two places since this confusion definitely occurs with some frequency.
The simplest distinction is that external modules are intended to be used with a module loader (either AMD or CommonJS) for all the reasons module loaders are good (plenty written on that topic for JS already). Think of internal modules simply as namespaces. Internal modules leave you with some JS (either many files or a single concatenated output files) that someone consumes by simply putting your file in scope (ex a

So if I'm making the actual entrypoint script for a page, is it possible to author an internal module while also gaining the ability to consume javascript modules?  Or am I required to be producing a module so that I can consume other modules?

Hi, here's the pattern I've been using for more than a year and a half now (for very large TS apps with more than a hundred source files). Though it may appear to stand in contrast to much of the design recommendations and advice you'll get from the TypeScript team, it has served me very well:

Although a big part of my development is for Node.js (I compile a single file that works both in the web and Node), I use internal modules only. I have a single namespace/internal module, let's call it App.
Every file contains a single class and look like this:

module App {
  export class SomeClass {
  ...
  }
}

I compile to a single .js output file (external module preference set to "CommonJS" but I don't think it matters as I never declare any).
I enable the compiled file to serve as a node module (when the node environment is detected) in this simple way:

module App {
  var runningInNodeJS = () => (typeof require == "function") && (typeof module == "object")

  if (runningInNodeJS())
    module.exports = App;
}

I import external CommonJS modules (in this example the Node file system module) in this way (note I avoid using TS keywords like "import" as they are not allowed in the scope of an internal module):

module App {
  if (runningInNodeJS()) {
    var FileSystem: typeof fs = require("fs");
  }
}

However since the Node definition files are for external modules, it will complain that type fs describes an external module and can't be used in this way. No worries, I have a set of regular expressions that will convert any external module definition file to an internal module definition file!
find: declare module \"(\w+)\"
replace with: declare module $1

find: \s*import.*
replace with:

It might seem somewhat unconventional to things this way (or even like an anti-pattern of some sort - indeed while developing this it did feel a bit like I'm fighting against the language in some way), but I can assure you it had made my life 10x easier, and doesn't have many drawbacks (apart for the compiler itself resisting my attempts at making development easier :) ).
I even a published a library using exactly this pattern:
https://github.com/rotemdan/lzutf8.js
Here's the compiled release file, I linked to the specific line where the internal module CommonJS export pattern is used:
https://github.com/rotemdan/lzutf8.js/blob/master/ReleaseBuild/lzutf8.js#L15
BTW I'm aware that the next version of TS will have ES6 modules but I haven't really looked deeply into them, and from what I've seen so far I don't think I'd eventually make use of them.

As for build automation, I agree that there's no "one" optimal build system, but here's my own current workflow:

All my compilation and builds (including compile-on-save) are now done through Grunt, which can be integrated into visual studio with the Task Runner Explorer VS extension: https://visualstudiogallery.msdn.microsoft.com/8e1b4368-4afb-467a-bc13-9650572db708

Recently I even disabled VS initiated TypeScript compilation entirely, instructions can be found here: https://github.com/Microsoft/TypeScript/issues/2294#issuecomment-78382591

In the Gruntfile I have a script (based on the Grunt API) that scans a set of glob paths for .ts files and generates a single references.ts file (it hasn't been published as a grunt plugin yet but may in the future):

function generateTypeScriptReferencesFile(filters, outFilename)
	{
		var fileNames = [];

		for (var i=0; i < filters.length; i++)
			fileNames = fileNames.concat(grunt.file.expand(filters[i]))

		function getPriorityByFileExtension(filePath)
		{
			if (/.+\.d.ts$/.test(filePath))
				return 0;
			else if (/.+\.ext.ts$/.test(filePath))
				return 1;
			else if (/.+\.spec.ts$/.test(filePath))
				return 3;
			else
				return 2;
		}

		fileNames.sort(function (fileName1, fileName2) { return getPriorityByFileExtension(fileName1) - getPriorityByFileExtension(fileName2) });
		fileContent = fileNames.reduce(function(result, filePath) {	return result + "/// <reference path=\"" + filePath + "\"/>\n";	}, "");

		grunt.file.write(outFilename, fileContent);
		grunt.log.writeln(fileNames.join("\n"));
	}
...
generateTypeScriptReferencesFile(["**/*.ts"], "_references.ts");

The script also orders the files by priority according to their extension (d.ts. and .ext.ts having the highest priority and spec.ts the lowest, this scheme would probably be extended in the future).

I compile the generated references.ts file with grunt-ts to a single outfile, where the debug output file will also contain Jasmine tests (originating from .spec.ts files) so the resulting file, having all its test suites integrated, can be tested both in the browser and in Node.

..Other project specific build steps..

An example Gruntfile.js (for LZ-UTF8) can be found here:
https://github.com/rotemdan/lzutf8.js/blob/master/Gruntfile.js

I guess I'll spend the next 5 days inventing my own build setup...  :-1:

@danquirk - It seems like every explanation I read only gives a partial understanding, but I never get a full picture that I can put into practice.
For example: I'm trying to publish just some typescript interfaces as a package for two projects to communicate along.  Literally no JavaScript will be produced (for now).
The top of my files read:
declare module MyProject {
    interface OneOfSeveral {
        ...

When I leave declare in, my .d.ts file contains the interface definitions.  But I can't understand why when I remove declare, suddenly my .d.ts file is empty.  What is going on that's different here?
To compound the confusion, I'm normally used to structuring my files so that the namespaces are represented in a directory structure.  There's a contradiction in my mind with explicitly naming modules and the way AMD works where the namespacing is usually just expressed through the filesystem.  At which point, should I even bother namespacing any of my typescript code?

So now I've also gone and split my interfaces into multiple files within a directory structure.  tsc doesn't complain, and I have .d.ts files.  But I have no clue how the interfaces that extend other interfaces are made aware of each other.  Also, I worry that this is all happening at the root namespace, so inside of typescript, all my classes are existing at the root.

@atrauzzi can you explain what you want to model? some concrete details would go a long way.

I'm kind of past it at this point.  I'm looking at JSPM right now, although I do hope that once TypeScript sorts out all these usability and code sharing issues, you guys will have an official plugin for JSPM.
I really love what you're trying to bring to the ecosystem, it's just not easy enough to use.

Just going to add a reference here: https://github.com/Microsoft/TypeScript/issues/2233
As I mentioned, it would be great if there was a Microsoft-maintained plugin that built to ES6 and integrated nicely with the rest of the ecosystem.
@mhegazy : One of the issues is that the system is complex enough that I definitely throw up my hands trying to come up with an explanation.  I'm not at all against a chat or email exchange with anyone who might want to tease out the sticking points.  More than happy to be the guinea pig! :)

@atrauzzi there is a lot of abstract conversations going on in this thread, and i am finding it hard to get to the bottom of the issue(s) you are running into, or the ones causing you to feel that the system is too complex. If i understand correctly you are basically asking for the compiler to support node resolution process as described in issue #247. is this correct? if not it would be great if you can share some concrete information on what is it that you are trying to do and how the compiler is not helping, this way we can come up with specific fixes to simplify the workflow.
On a related note, @vladima is working on a proposal that handles some of the common module issues as specified in #2338, take a look and let us know if that would simplify your use case.

@mhegazy
Regarding #247, I think that should be amended to support JSPM, which I think is the best JS workflow I've seen to date.  To give you some some idea of the impact, I went from frustrated with TypeScript, to coding and running working ES6 in the span of a day.  Whatever that project is doing, it was basically everything necessary to solve my issues.
Okay, with that established, I'll give this another shot and I'll try to isolate it in terms of what I go through in trying to use typescript.  This is gonna be pretty dry! ;)
The initial authoring of my first typescript file brings up a lot of questions where I have to stop what I'm doing and research modules.  When I see modules, I think namespaces and so my first attempt is to use them as such.  This means that I'm going to create a hierarchy of directories containing files.  What confuses me there though is that it looks like modules have no corollary in ES6.  So I don't know if they're denoting a TypeScript design-time boundary, or a compiled-JavaScript boundary.  Moreover, their purpose is ultimately unclear, given that there are explicit export keywords, similar to ES6.  The behaviour of exporting when nested in a module declaration is odd.
The module/namespacing confusion gets more difficult when I'm trying to understand the impact it has on my ability to reuse code within my own project.  When am I required to explicitly import, and when is an exported item from another file is available in my current scope?  Because I have to consider both static and design time, I end up very confused.  Even more befuddling is that there are two import mechanics.  One is a straight up keyword, and the other is a frightening comment-hack.  I just don't know when I'm safe to use something anymore because I don't know what keywords or constructs are going to require additional wiring from me at build time.  Because TypeScript is your own ball game, why not just make the import keyword support importing .d.ts files, .ts files AND AMD/CommonJS names?
But now that exposes a huge huge huge point of conusion (I'm glad I typed it):  What happens when you import a .ts file?  Is the file concatenated to the top of the including script?  Or is it simply added to the list of files to be built and added as an AMD/CommonJS reference?  If it is added as an AMD/CommonJS reference, will the file be built in such a way that loaders can reference it (preserving folder hierarchy)?  Very very very very confusing and unpredictable.  Even if this is an "everybody is different" situation, TypeScript's documentation can't just gloss over the fact that what happens to translate imported functionality needs to be documented and ideally tutorialized.  Right now though, people are kind of left with no guidance and frankly I will do everything possible to NOT have to configure a JavaScript build setup.  I'll mention JSPM again here.
Continuing along this packaging+runtime thread, is the fact that if I want to publish interfaces to a package, I'm completely without a clue as to how to go about setting that up.  I made a hamfisted attempt on Thursday to do this and just walked away from it.  While I was able to define a hierarchy of namespaces full of interfaces, I had no way of producing a single .d.ts file (really that's all this library was going to produce) and then making a package that TypeScript would automatically become aware of once added to a project (maybe something JSPM can help with?).  I was able to generate multiple .d.ts files, but that seemed impractical.  I'd rather someone be able to just add one .d.ts file as a reference and get my whole library declared.  But then would that introduce names into their file or would they have to then start importing things in cases where I wasn't just exporting interfaces?  How would their code find code in my package?  Yikes.
So yes, I can author typescript files and pretend like I know what I'm doing.  But when it comes time to compile, I feel like the compiler isn't clear on what it needs for one file to be able to resolve all its dependencies.  I feel like it's unclear as to how the code I author is going to be called into at runtime, or even where it's going to live, both in my project and in packages I need to make.
I'm really hoping that you can glean something from this description.  While I know it is mostly a summary of what I went through in this discussion, I just have no idea how to describe it any better.  What might be nice is if you asked me specific questions based on all this.
What I can suggest is based on what I've seen from JSPM and how quickly I got up and running with it:

You need to do something to make building TypeScript less or even no work for the developer.
I'm not sure module declarations are useful given that modules are usually the entire file.  They may be adding an additional layer of containment that have no counterpart in the runtime ES5/ES6 universe.
I'd be willing to bet that if you got TypeScript integrated as a language option within JSPM, I'd be able to learn my way out of this confusion.  The simple reason being that JSPM isn't just traceur/babel.  It includes package importing, loading mechanics, ES6 transpiling and a full build process. I know that when I import a specific string-name in my ES6 file, it's gone and mapped that to a convention for each package.
There needs to be a full and comprehensive guide on how to setup, author and build a TypeScript package.  Again, ideally abiding by whatever is necessary to be loaded by JSPM.

It's all fairly abstract because this is as far as I've gotten.  If at the end of the day this isn't enough, then the only thing I can say is: I have absolutely no idea how to set up my project to use TypeScript, there's just too much going on and there are too many sideffects and interactions that cross design, build and runtime boundaries to devise a mental model for it.

Thanks @atrauzzi for the details. i will need to read this again, but i got a few of concrete points, let me summarize some action items:

Generate single .d.ts from external modules representing the package public surface area, instead of multiple (partially #17)
Better support load correct module sources (.ts) or definitions (.d.ts) based on the module system (#2338)
Add JSPM support (#2233)
Add documentation/walk through for creating, loading, publishing and reusing your first module
Rename internal modules to namespaces to avoid confusion with external modules (#2159)

Again i will need to read this again in the morning to get more details. Thanks for the feedback, really appreciate it.

A quick addendum to namespacing corrections: Be sure to also go through it with a fine tooth comb and document their impact on design, build and runtime.  There needs to be some emphasis on what they are to typescript and what they are to compiled code.
I'm sure you'll infer a few more details from my story above over time, but again - please ask me any time if you want to pick at a detail.  I am still very interested in TypeScript and would love to see it as a language option just like traceur and babel in JSPM.  That ecosystem really seems to "get it" and is coming together nicely.

I think it's worth noting that TS as it stands does an excellent job of supporting the various ways in which JS is currently used. It's best understood as a tool for adding static type checking to the existing JS ecosystem(s), so it has to be flexible.
Some of @atrauzzi's questions are similar to questions I had when I started with TS and it was frustrating that they did not seem to be clearly answered anywhere. Now I get it, it seems like an elegant mapping to how JS is used in the real world.

But now that exposes a huge huge huge point of confusion (I'm glad I typed it): What happens when you import a .ts file? Is the file concatenated to the top of the including script? Or is it simply added to the list of files to be built and added as an AMD/CommonJS reference?

Neither. At the top of a module, when you say:
import x = require("x");

you are saying two things:

You are telling the compiler that this is a module whose own declarations should not contribute to the global namespace. It may export specific things, but otherwise all its contents are private.

You are telling the compiler to generate this in the output:
var x = require("x");

(for CommonJS, or something conceptually equivalent if you choose AMD). You are also telling the compiler, only at compile time, to find type information for "x". It tries the following:

Is there a declaration anywhere in the files passed to the compiler that says module "x" { ...? If so, assume that provides the type information for x.

Is there a file called x.ts relative to this folder, or the parent folder, or any ancestor folder? If so, read it for the type information (but don't generate any code from it, as it is going to be passed to the compiler for separate compilation just like the present .ts file).

So when distributing JS packages, I should also include a .ts file alongside every file so that TypeScript can "prefer" it when searching for dependencies?  Is this documented behaviour?

Going across package boundaries is totally different, unfortunately. TS doesn't know anything about npm (for example). When the consumer of an npm module says:
import x = require("x");

TS doesn't know that the implementation lives in ../../node_modules/x where there is a package.json file that might contain further helpful information.
The workaround is that the consumer must obtain from somewhere (e.g. DefinitelyTyped) a d.ts file that contains:
 declare module "x" { ... }

The consumer has to separately arrange to reference this file in their compilation step, which undermines the otherwise automatic nature and experience of npm packages.
But a package manage like jspm that supports transpiler plugins could make such assumptions. I've posted some vague wishes about this under issue #2233.

Fantastic, thank you so much for all this information :)
Hopefully it's enough to smooth the workflow so that I can switch over to TS at some point in the future!

authors: atrauzzi danielearwicker danquirk mhegazy rotemdan


text:
Starts to lag after editor-widget with large content pops up

From @emiljohansson on April 15, 2018 14:19

VSCode Version: 1.22.2
OS Version: macOS Sierra 10.12.6

Steps to Reproduce:

I am using JSS (9.0.0) in the screenshot example.
When adding a comma at the end of the line, within the createStyleSheet call, an element with the class name editor-widget pops up. The content of the box is 10001 characters long. It seems to be cut of after that, ending with "revert" | "unset…. Let me know if you want me to paste the content.

In the screenshot, the cursor start to lag when I navigate back and forth. Same when I navigate between editors.
Does this issue occur when all extensions are disabled?: Yes

Copied from original issue: Microsoft/vscode#47909

From @emiljohansson on April 15, 2018 18:15
I wanted to add that if I close the widget, the lag remains going between editors, but the cursor lag seems to go away.
I also tested setting the end variable to 500 and that removed the lag: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/parameterHints/parameterHintsWidget.ts#L394

Here's the code I tested this with:
import  jss from 'jss'

jss.createStyleSheet({
    base: {
        background: 'blue',
    }
})

Moving over the ts because the signature help requests themselves here seem to be taking a long time:
Rsponse received: signatureHelp (324). Request took 395 ms. Success: true

Each one is between 350 and 500ms

Looks like we are spending most of the time serializing the union type..

looks like a duplicate of https://github.com/Microsoft/TypeScript/issues/23458. should be addressed by https://github.com/Microsoft/TypeScript/pull/23543

authors: mhegazy mjbvz


text:
Indexed Access Types that should be the same as a given types are somehow different than that type, under strictNullChecks

TypeScript Version:  3.5.0-dev.20190411

Search Terms:
Indexed Access Types
Lookup Types
strictNullChecks
Code
type Foo = {bar: undefined} | {bar: string};

const b1: {bar: Foo["bar"]} = {bar: undefined};
const b2: Foo = b1;
const b3: Foo = {bar: undefined};

Expected behavior:
This should compile with strictNullChecks on. I expect {bar: Foo["bar"]} to be the same thing as Foo in this case.
Actual behavior:
running tsc --strictNullChecks .\bug.ts result in:
bug.ts:4:7 - error TS2322: Type '{ bar: string | undefined; }' is not assignable
 to type 'Foo'.
  Type '{ bar: string | undefined; }' is not assignable to type '{ bar: string;
}'.
    Types of property 'bar' are incompatible.
      Type 'string | undefined' is not assignable to type 'string'.
        Type 'undefined' is not assignable to type 'string'.

4 const b2: Foo = b1;
        ~~

Found 1 error.

Playground Link: Link
Related Issues:
https://github.com/Microsoft/TypeScript/issues/29042
https://github.com/Microsoft/TypeScript/issues/21975 This one is extremely similar but it and the ones it was marked as a duplicate of were closed. Is this a regression?

Might be fixed by #30779

Might be fixed by #30779

Confirmed!

authors: Ryan1729 RyanCavanaugh jack-williams


text:
Include selected local subdirs in baseline-accept

Working on #13217, was not able to get a transpile to test to accept, solved in response to @RyanCavanaugh https://github.com/Microsoft/TypeScript/pull/13217#issuecomment-273843791.
This PR is quick and dirty.  It may be sufficient as-is, or may elicit a discussion re: a more elegant way to do this...  Should it just be a completely recursive solution (search all subdirs), or are only selected folders intended to be named in $ jake baseline-accept?

Hi @pcj, I'm your friendly neighborhood Microsoft Pull Request Bot (You can call me MSBOT). Thanks for your contribution!
You've already signed the contribution license agreement. Thanks!
The agreement was validated by Microsoft and real humans are currently evaluating your PR.
TTYL, MSBOT;

Please update the gulpfile as well - they need to do the same thing. )And please don't ask why we have two build files to do the same thing 😢  )

should we just drop the gulp file?

I would vote for getting rid of the jakefile, or at the very least turning all the jake targets into aliases for the gulp targets. Having two implementations is getting old.

Kind of funny you each proposed getting rid of the opposite file :smile:.  So which one are people using?  I went with jake as this was part of the instructions in the CONTRIBUTING.md, but I have no preference (It was the first time I had encountered this particular build tool).
If you have a consensus, I'd be happy to delete that file and update the documentation.

I still use jake. just muscle memory though. gulp seems fine, my only concern is that it is slower.

should be covered by the change in https://github.com/Microsoft/TypeScript/commit/abae1bd13680e1fd13deb2f827563770181d071b

source: gharchive/pull-request

authors: RyanCavanaugh mhegazy msftclas pcj


text:
Fix #22866: Condition checking for name collision of generated variable names on emit happening

Fixes #22866

Looks like there is lint :(

authors: mhegazy sandersn


text:
Do fewer calls to getRelativePathToDirectoryOrUrl when writing sourcemaps

Shaves about 35% off time to build tsc.js. We should do more profiling / optimization here as this function is currently the vast majority of time spent building the project

Didn't seem particularly slow - it does do some array allocations and string walking, but was simply being called too many times

Understated the magnitude here; time to run node lib\tsc.js -b -f src\tsc down from 55 seconds to 35 seconds

Didn't seem particularly slow - it does do some array allocations and string walking, but was simply being called too many times

Mmm, caching like this will definitely help in the common case where there's a ton of mappings for the same files, but if, for example, there's 1000 files each with only a few mappings (so lots of tiny projects, which is the logical extreme of optimizing a project this way), this won't help nearly as much. (May even hurt from increased memory pressure) Which is why I also want to understand why it was so slow itself. It looks like split (and slice) may be part(s) of the issue, since combined they take most of the function runtime. (0.9/1.2 ms) Those both correspond to new array allocations, which makes sense. We can likely reuse a single (set of) arrays for the internal calculations (since it just returns a string anyway) and remove those allocations. Naturally, it's good to keep the cache too, but that'd probably improve the worst case significantly.

authors: RyanCavanaugh weswigham


text:
Fix formData constructor in lib.d.ts

Fix formData constructor in lib.d.ts

Hi @Breate, I'm your friendly neighborhood Microsoft Pull Request Bot (You can call me MSBOT). Thanks for your contribution!

This seems like a small (but important) contribution, so no Contribution License Agreement is required at this point. Real humans will now evaluate your PR.

TTYL, MSBOT;

thanks @Breate for the change. this file is autogenerated and we do not hand edit it. All DOM types are generated from IE's webidl DOM definitions. we are in the process of opening this generation script as well. please file an issue to track adding the additional argument to the constructor.

Looks like an issue already exist for this: #1074

authors: Breate mhegazy msftclas


text:
Fix classification for class expression

Fix #4483

:+1: :cake: :fish_cake: :cookie:

nom :coffee:

Don't forget to merge into release-1.6

authors: DanielRosenwasser yuit


text:
UIButton imageView should return nil for system buttons

UIButton.imageView should return nil for system buttons. Currently, it returns the proxied imageView.

I'm curious if this holds true after calling setImage:forState?  I'm also not convinced we should bother fixing this corner case.

Lower priority issue, not much could be done with nil return value

authors: jaredhms oliversa-msft tadam-msft

repo: Microsoft/WinObjC

license: MIT


text:
Re-applying "Updating all VS projects to target the RS1 SDK. (#1122)"

This change is

@asimonov-msft when is this going to be merged, are we waiting for something?

authors: asimonov-msft rajsesh-msft


text:
XamlTreeView C++ fails to compile (C# okay)

I am having (possibly) the same problem as the person over in issue #557, but random tweaking the project settings this way and that doesn't seem to help. I am using Visual Studio 15.3.0 Preview 7.0, and have also installed SDK 16232 with all the trimmings. Other UWP C++/CX samples build okay, so I think my general MSVS install is probably sound. The C# version of XamlTreeView project builds and runs okay. Any insight appreciated.
1>------ Rebuild All started: Project: TreeViewControl, Configuration: Debug x64 ------
2>------ Rebuild All started: Project: TreeView, Configuration: Debug x64 ------
1>pch.cpp
2>pch.cpp
2>c:\users\there\source\repos\windows-universal-samples\samples\xamltreeview\cpp\pch.cpp : fatal error C1192: #using failed on 'C:\Users\there\source\repos\Windows-universal-samples\Samples\XamlTreeView\cpp\x64\Debug\TreeViewControl\TreeViewControl.winmd'
2>        'The system cannot find the file specified.'
2>Done building project "TreeView.vcxproj" -- FAILED.

With some more clicking I have found that building the C# solution targeting 16232, and then re-opening the C++ solution, it picks up the winmd correctly. It is "rebuild all" in the C++ solution (which I was always selecting without much thought about it) that results in the fail.

Ah, there is a missing dependency in the C++ sample. The TreeView project needs to be marked as dependent on the TreeViewControl project. I'll include that in the next update, thanks.

authors: oldnewthing therealkenc

repo: Microsoft/Windows-universal-samples

license: mit

license_source: bigquery


text:
Issues/Crash table - right click to open in new tab, once returned to table it jumps back to the top.

Describe the solution you'd like
If I right-click on any issues to open them in a new tab, then visit one or more opened tabs, when I return to the table it jumps back to the top which takes me out of context.
Describe alternatives you've considered
Avoid visiting the tabs until I have opened them all in separate tabs (tab hell)
Additional context
N/A - easily re-creatable in Chrome and Safari (Mac)

Thanks for reporting this! I've filed a bug item for our team to track this and will post here with any updates.

repo: Microsoft/appcenter


text:
Adding route constraints to versioning doesn't pick them back up on VersionedApiExplorer

I have a custom route constraint that I've added that subdivides our application by picking up a custom attribute on the controller and matching on incoming requests by overriding DefaultDirectRouteProvider and adding the constraint to each controller based on each HttpControllerDescriptor coming in.  I've got that working and performs wonderfully with api versioning for incoming requests.  Where I'm struggling is subdividing Swagger based on that same premise.  I've added the ConstraintMap to the DefaultInlineConstraintResolver like so
var constraintResolver = new DefaultInlineConstraintResolver()             {                 ConstraintMap =                 {                     ["apiVersion"] = typeof(ApiVersionRouteConstraint),                     [AgentConstants.RouteConstraintKey] = typeof(AgentRouteConstraint),                 }             };             var agentRouteProvider = new AgentDirectRouteProvider();             config.MapHttpAttributeRoutes(constraintResolver, agentRouteProvider);
It seems like I could override GetGroupName of VersionedApiExplorer and return the string and possibly break it back out in the groups on the swagger side and maybe use an IOperationFilter but I'd like to achieve somewhat of the same goal to have a route constraint applied to the list of applicable routes.  Ideally I can use that same constraint to only show the values in Swagger UI.  Some guidance would be appreciated.

Sorry, but I'm not sure follow. What would the resultant URLs look like? I'm not sure what you mean by subdivide. If you're able to outline a basic illustration or description of what you expect success to look like, it would be helpful.

Sure.  So I'm actually creating duplicate controllers in a different namespace so that I have Agent "A" in namespace "A" and Agent "B" in namespace "B".  I'm using a route constraint that looks up the expected agent using a header "api-agent" to signify which agent namespace to apply to.  The attribute is being applied to a base ApiController which is inconsequential to the implementation.  Then the [ApiVersion("1.0")] Tags are being applied.  It is all done with Route/Prefix attributes.  No mixing.  My expected result is that I can use the same route constraint against the swagger api to only give the versions available to that "api-agent" tag.  In my route constraint, I have made it so that can work via header or URI.  My hope was that when VersionedApiExplorer gets called it would being calling the route constraints in the same way to match the controllers.  Right now it seems like it picks the first matching route in each case.  I think I could subdivide by overriding GetGroupName in VersionedApiExplorer and then parsing it back out in the api descriptions but that feels ucky and was hoping for the cleaner solution. My ideal is that the same route constraint just evaluates the request coming into swagger and calls that same route constraint.  Resultant URLs would look like localhost:8000/v1/swagger?api-agent=A or B but what that returns would be dependent on A or B.

I see. This seems like it's more on the Swagger side. In Swashbuckle, I'm not sure how you get in front of the request. I don't think even the group name helps because you have to wait for an incoming request to know what the client is requesting. If you can somehow get to the incoming request, it shouldn't be a big deal change things. The API Explorer works completely off of known data. There's nothing used from an incoming request.
It sounds like what you need is a custom Swagger generator. You can probably extend a built-in one. You can probably do it with a custom IDocumentFilter or IOperationFilter. Otherwise, it seems you cannot use configuration.EnableSwagger and you'll have to write you own handler that does the filtering the way that SwaggerDocsHandler.cs works. That seems to be the only way to get to the corresponding request.

That's kind of what I was figuring.  I went down that path and GetRootUrl was not available so it started to snowball.  With GetGroupName I can make it sort of work because instead of returning V1.0 I can return AgentA-V1.0 and that would give the extra subdivision and I can break it back out in MultipleVersions.  The reason I thought it might be possible with VersionedApiExplorer is because when I looked at the way the ApiVersionRouteConstraint worked in the match I saw:
if ( routeDirection == UrlGeneration ) {     return !IsNullOrEmpty( value ); }
That made me believe there must be a way that URL's where being generated and somehow I could back feed the appropriate Agents in a similar way.  I'm so close I can taste it.  Enabling this scenario allows for a very clean separation for various agents but the "copy-paste" scenario without great effort.  Really appreciate the hard work on api-versioning.  It has enabled a really clean way to handle versions and nearly everything I could've wanted has been implemented already.

So I've made a little progress on the VersionedApiExplorer and figured out that I can override ExploreDirectRouteControllers and add metadata to the returned collection of VersionedApiDescription in the Properties of that for each mapped route.  I was then going to  extend InitializeApiDescriptions to return an ApiDescriptionGroupCollection representing the multiple versions v1 for Agent A and v1 for Agent B.  I then noticed that the Flattening of the versions is also tossing the duplicates as a result.  I'm trying to avoid copying and making my own complete version of VersionApiExplorer.  By doing that I could then create my own version of UseSwagger which adds in the route constraints and ties that using the *IDocumentFilter like you suggested.  Right now it seems like if I replace the ApiDescriptionComparer with one that knows about the agent routes so it stops flattening out all of "duplicates" and then copying the ApiVersion to an overridden version that will also contain the agent information and break it back out in InitializeApiDescriptions  that will get me over to swagger and now its completely my problem.  Am I missing anything in there?

Sounds like you're on the right track. Overriding InitializeApiDescriptions would probably be the simplest. Call the base implementation and then apply the filtering at the end. The default behavior bucketizes by API version so you don't want any duplicates there.
In Web API, the IApiExplorer doesn't support the concept of grouping. I had to beat it into submission. Other frameworks like Swashbuckle and NSwag depend on the IApiExplorer contract. The API versioning flavor flattens the grouped list to adhere to the contract. At least in Swashbuckle, a filtering callback is defined to determine whether a descriptor matches. I provided an extension method to get the group name so it's easy to integrate with.
Another approach to subclassing would be to use the Decorator pattern to apply the filter to the results. Creating the instance would look something like:
var apiExplorer = new TenantSpecificApiExplorer(
    "tenant",
     new VersionedApiExplorer( config, options ) );

You implementation just needs to call the inner IApiExplorer and then filter the results. I'll leave it up to you as to whether that's better than subclassing. It should be easier to test. ;)

So I started to think of a suggestion (adding a version factory) and then it hit me.  As I went to describe the feature and discover for it I found the part I was missing. It was that the ApiVersionAttribute was in fact the provider of ApiVersion.  I missed it in the discovery phase that the ApiVersionModel was using the ApiVersionAttribute as the factory or provider for ApiVersion.  If I extend both the attribute(s) and the ApiVersion that will get me down through the IApiExplorer without having to redo all of the comparison.  Instead I just need to override the comparison for ApiVersion and bingo bango I have a different version automatically segmented.  I still have to figure out Swashbuckle. The groupname is still the correct concept.  I want V1, V2, V3 but when I pass in Agent=A I want to narrow the results to that segment.  I really appreciate the help, sometimes it helps to talk through stuff.  It was like pair programming :) Also, great work on this feature.  Literally everything to extend it is there once you understand how the model was put together.  I really learned a lot.

Remember that API version-neutral does not mean no API version; it's exactly the opposite. It means all, any, or no API version. If a controller is IApiVersionNeutral, then no API versions will be provided. The API Explorer adds API version-neutral actions to every discovered API version. Also keep in mind that it's a mistake to have a duplicate, API version-neutral route across namespaces. If a controller is API version-neutral, "...there can be only one!" ;)  There's no way to make a selection otherwise because the choices are ambiguous.
PopulateApiVersionParameters is just adding the API version parameter, wherever that may be. The API Explorer doesn't know how or where the API version parameter is. While it may seem like it should know that, it would limit it's design and usefulness to only API versioning methods it knows how to deal with. Instead, it relies on the IApiVersionParameterSource which knows exactly how to describe the parameter to be added. Today, this is still limited to query, header, path, or media type, but that will probably cover everything for all time. The IApiVersionReader is, therefore, also a IApiVersionParameterSource. This could get a lot more complicated for the API Explorer because an IApiVersionReader can use the Decorator pattern to compose multiple styles. Each style can add a parameter. For example, an API might allow for a parameter in the query string and header; thereby resulting in two parameters. As long as each composed IApiVersionReader and, hence, IApiVersionParameterSource can say what the name of the parameter is and where it's location is, the API Explorer knows how to build an appropriate ApiParameterDescription. This is all necessary because the API version is not formally defined in your API model anywhere. Ultimately, PopulateApiVersionParameters does not provide an API version for IApiVersionNeutral actions because which API version would you provide? Furthermore, providing no API version is still valid. I hope that clarifies how it works.

It does clarify it a ton.  As with any "HACK" it turns out that worked out really well.  So I use PopulateApiVersionParameters which gets to see even the Neutral ones.  Leaving my extra attribute on my base controllers for the segmentation was definitely the way to go for that exact reason you mention.  So given that, when the ApiDescription comes across I merely need to convert it back to VersionedApiDescription and then convert and replace the ApiVersion with my extended AgentApiVersion with my additional metadata and overrides for equality and hashing.  The ApiDescriptionComparer gets replaced for extended implementation doing all of those same things using the AgentAtttribute provider I created that stores them on the Properties.  That prevented the complete flattening of all the V1-A and V1-B urls that look exactly the same. To go from V1, V2 to V1-A, V1-B, V2-A,V2-B, I did override InitializeApiDescriptions and looped the groups/descriptions and just started a new GroupCollection and GetOrAdd with the ApiVersion which was now the AgentApiVersion so it split it automatically through the hash/equality overrides. Like you mentioned GroupName was the secret to bridging the version over to Swashbuckle.  I only needed it to be unique in order to get over to Swashbuckle.  Once over there I redescribed the routes and replaced information back the way I wanted it.  The trick was to add Swagger/UI routes for each agent passing that into the versionSupportResolver portion of  swagger.MultipleApiVersions to narrow to that particular agent.  I hit a couple bugs adding the swagger routes multiple times, mostly had to remove the route it creates and add it back with a unique name.  Again I really appreciate all the help.  I'm going to see if I can put some PR's in for the stuff I hit.  I think what is really missing on the Swashbuckle side is a request metadata provider.  I think since I'm using autofac I could've resolved the HttpRequestMessage off of their CustomProvider but that would've been too ucky.  Having metadata about the request I could've done it all with document/operation filters and had a much cleaner and lightweight solution.  Thanks again for your time.  Hope this conversation helps someone out at some point.  Have a great weekend.

Seems like you were able to resolve your issue. Feel free to come back if you still have trouble. Thanks.

authors: cberthold commonsensesoftware

repo: Microsoft/aspnet-api-versioning


text:
Cannot pull microsoft/aspnetcore - Failed to register layer

Pulling microsoft/aspnetcore image fails.
Execution of  docker pull microsoft/aspnetcore command results in:
Using default tag: latest
latest: Pulling from microsoft/aspnetcore
bce2fbc256ea: Already exists
53a0ccfb7e6f: Extracting [==================================================>]    148MB/148MB
05db938a42bb: Download complete
19a9c8f9472b: Download complete
f314af833261: Download complete
78e4cc48f3b5: Download complete
85a07057fe9a: Download complete
9be7ffeb20c4: Download complete
c2e6633a2cc5: Download complete
312abcf6e5bb: Download complete
4e3ebdf680a9: Download complete
failed to register layer: re-exec error: exit status 1: output: remove \\?\C:\ProgramData\Docker\windowsfilter\5f1cdf312dfc041dcf5ad4e548967b14c4995c9c8d4ddc2277baf9411c78562d\UtilityVM\Files\Windows\servicing\Packages\Microsoft-OneCore-Containers-Package~31bf3856ad364e35~amd64~~10.0.14393.0.cat: The process cannot access the file because it is being used by another process.

System specification:
CPU: AMD Athlon FX-4100
RAM: 12GB,
MOTHERBOARD: Gigabyte GA-970A-D3
OS: Windows 10 Pro
Kernel Version: 10.0 15063 (15063.0.amd64fre.rs2_release.170317-1834)
Docker for Windows: Docker version 17.09.0-ce, build afdb6d4

I have had this but not with this image. The issue seems to stem from the version being pulled when not using specific enough tags and the compatibility with the image that Docker decides to actually pull. Obviously this is all dependent on when you actually did the pull and your version of docker at the time, which you have provided above so I reckon this is explainable:
TL;DR - On the assumption you are still running that same version of Windows 10 and the same version of docker stable (why would you be?), the solution for you is likely to be to do docker pull microsoft/aspnetcore:4.7.2-windowsservercore-ltsc
So, why did this happen?
You're using Windows 10 1703, but when you did the docker pull, Docker (at version 17.09!) assumed you asked for a build of Windows Server 1709 (not to be confused with docker's version) because (that version of docker) will pull the latest OS version unless you specify which container OS version you want. Build 1709 of Windows Server (in the image) isn't backwards compatible with Build 1703 of Windows 10 (your OS). If you had updated docker to 17.10 (which was only released as an edge version), it would have pulled the ltsc image and saved you the hassle. See this issue and resolution for info:
Add support for Windows version filtering on pull - https://github.com/moby/moby/pull/35090
You're just a little unfortunate that you did a pull around this time and didn't have the latest (edge) version of docker that could detect compatibility and pull the right image. This note on the readme page is important in your context.

Note: Multi-arch tags, such as 4.7.1, have been updated to use windowsservercore-1709 images if your host is Windows Server 1709 or higher or Windows 10 Fall Creators Update (Version 1709) or higher. You need Docker 17.10 or later to take advantage of these updated tags.

Hopefully that makes sense.

authors: lwsrbrts oskiFP

repo: Microsoft/aspnet-docker


text:
FTP deployment failure to an existing function app

Plugin name and version
com.microsoft.azure.azure-functions-maven-plugin:0.2.0-SNAPSHOT
Actual behavior

@bsaby Just as the log shows. It it because the jar file is been occupied by the service. To solve this problem, you and add <stopAppDuringDeployment>true</stopAppDuringDeployment> in the plugin configuration

I can't repro this issue after adding the configuration <stopAppDuringDeployment>true</stopAppDuringDeployment>

authors: bsaby jdneo

repo: Microsoft/azure-maven-plugins