TypeScript VS ScriptSharp – What’s the tradeoff’s?

I am about to build a large scale Javascript application and I want to build it in more structured way. Jquery is will use for css effects. The server side will be in c#. Can you share your knowledge and experience, which is better? Which one is more feature rich? Which is better documented? Is type script really strongly type? Also, for the long run, ScriptSharp is one-man-show (As I understand it) and Typescript was built by Microsoft. Thanks

Why is Web Essentials 3.6.5 not compiling Typescript?

I just updated my Web Essentials to 3.6.5 and my *.ts files are not being compiled to javavscript. Also, when I go into Web Essentials-Typescript-Options the only option displayed is Show Preview Window and the right pane says CoffeeScript not Typescript. Where are the other options?

typescript definitions for openLayers

Here's a function I need to use in typescript code: ol.inherits(child, parent); How to add a definition for that function in OpenLayers.d.ts file? https://github.com/borisyankov/DefinitelyTyped/blob/master/openlayers/openlayers.d.ts Thank you in advance for any help!

Typescript can't be compiled in vs code: error TS5007

I just installed vs code v1 (the latest version) and typescript v1.8.10 (latest version). I followed the exact instruction from vs code website but can't get vs code to build the simplest typescript file though I can manually build it by running tsc command in git bash. The output from the vs code is: error TS5007: Cannot resolve referenced file: '.'. error TS5023: Unknown option 'p' Use the '--help' flag to see options. This is the my helloworld.ts file which really can't be simpler: class

Typescript How to bubble up angular2 custom event

Parent template: <ul> <tree-item [model]="tree" (addChild)="addChild($event)"></tree-item> </ul> Tree item template: <li> <div>{{model.name}} <span [hidden]="!isFolder" (click)="addChild.emit(model)">Add Child</span> </div> <ul *ngFor="let m of model.children"> <tree-item [model]="m"></tree-item> </ul> </li> For above example, parent receives addChild event only from the root tree-item (i

Typescript Why is there so many TS errors even though it compiled fine?

I'm currently trying out TypeScript and combining it with some other JavaScript libraries. I can see the benefits of TypeScript when used with Vanilla JS and wanted to try out the whole idea of using various libraries in combination with declaration files (.d.ts) to have everything be in TypeScript. I took the three.d.ts file off of the DefinitelyTyped repo so it should be an official and clean copy. I ran tsc app.ts and my app.js file looks fine from the compilation. However, I got a string o

Typescript Conditional member type based on other members types

Is it possible to specify multiple possible member types based on specific conditions ? For example, giving the following type: interface DataItem { value: boolean | Date | string | string[]; options: undefined | string[]; } I would like to specify that if: value is of type boolean or Date then options must be of type undefined. value is of type string or string[] then options must be of type string[]. Is there anyway today to specify the above constraints in current version of Ty

Typescript enforcing type signature for toString

how do I force the compiler to not overload toString? The closest I have got is to use the never type, but never is still allowed to be implicitly assigned to a var the compiler only complains when something is done with the variable. Who is going to remember to explicitly declare toString calls as strings? type ArrayToStringMethod = { (this: { join(a: string): string, length: number }): string (this: any): never // if this overload isn't here typescript uses // Object

How to use TypeScript definition files from the @types npm repository when --module is 'none'

how can I use TypeScript definition files via @types if the compiler's module system parameter is set to 'none'? For example, when using the type definitions for the express web server: npm install @types/express with the following tsconfig.json { "compilerOptions": { "module": "none" } } This code fails: import * as express from "express"; export module Web.Server { const app = express(); } with the error message: Cannot use imports, exports, or module augm

Typescript Ionic 2 - set timeout to pop page to root after X seconds

Currently when a user submits a form it shows and thank you overlay - after 2.5 seconds I want the overlay to disappear. My currently code looks like this. import { Component } from '@angular/core'; import { NavController, ViewController } from 'ionic-angular'; import { Storage } from '@ionic/storage'; @Component({ selector: 'finish-page', templateUrl: 'finish.html' }) export class FinishPage { constructor( public navCtrl: NavController, public viewCtrl: ViewCon

Typescript definition when pulling from dist folder

Is there a way to define types for classes when you pull them from a dist folder? Aka, sometimes I'll do... import MyClass from "dist/classes/myClass.ts"; const instance = new MyClass(); How do you write a .d.ts file that works for this case too, or is that possible?

Typescript Make InfiniteScroll with Ionic 3

I'm using symfony3 and FosRestBundle for backend and Ionic 3 for frontend. I have followed the documentation of Ionic to make an InfiniteScroll but I didn't reach to do it. Just the loading text and the spinner appear and no data is pushed. This is the backend action : /** * @Rest\Get( * path="/articles", * name="api_article_list" * ) * @Rest\QueryParam( * name="limit", * requirements="\d+", * default="5", * description="Maximum element per page" * ) * @Rest

Typescript How to configure VS Code Auto import?

Is there a way of tweaking TypeScript Auto import feature in Visual Studio Code? As an example, observe the following attempt: The added line by the Auto import was the following: import { Pins } from '../types/index'; I would like it to be added straight away without the comma, in respect to TSLint, and without the /index path, due to my subject sense of aesthetics, like the following: import { Pins } from '../types' Is there a way of saving those few "extra" keyboard hits?

Typescript Calling http post after calling http get

I am working with an Angular 4 application and I am trying to retrieve a shipment id to store in my transaction before writing the transaction to db. Each call is working by themselves, but how can I make sure that the shipment Id value comes through before making the post call? Below is the code I have: //From component saveTrans(): void { //Retrieving Shipment Id if (this.newTransaction.VehicleId != '') { this._data.getShipmentId(this.newTransaction.VehicleId).subscribe(s => thi

Firebase cloud functions typescript ReferenceError: google is not defined

I have a cloud function that make a request to google map api to get geocode location info from latlng. when i make the request it show that error in error in the logs ReferenceError: google is not defined at /user_code/lib/file_name I don't what the reason behind that and i added the typed package to package.json file. package.json { "name": "functions", "scripts": { "lint": "tslint --project tsconfig.json", "build": "tsc", "serve": "npm run build && firebase serve --o

Typescript Error while running nestjs in production mode, cannot find module

I have implemented a generic class as below which might be causing the problem, import { Logger } from '@nestjs/common'; import { PaginationOptionsInterface, Pagination } from './paginate'; import { Repository } from 'typeorm'; export class EntityService<T> { private repository: Repository<T>; constructor(repository) { this.repository = repository; } async getEntityWithPagination( options: PaginationOptionsInterface, )

How to extend Material UI 3 theme Typescript definition with the Material UI pickers theme

I try to extend the Material-UI theme to incorporate the Typescript typings of the Material-UI-Pickers, for the following (latest) versions: "@material-ui/core": "^3.9.2", "material-ui-pickers": "^2.2.1", There's a mention at the bottom of the Material UI picker page, explaining that the theme can be augmented thanks to Typescript Theme augmentation. It recommends to do this: declare module '@material-ui/core/styles/overrides' { import { MuiPickersOverrides } from 'material-ui-pickers/t

Typescript Unit test using karma-jasmine with child process

Greeting, I'm currently trying to create tests using karma-jasmine on a application using Angular and Electron. I encountered a problem with simple-git which use child process and it seems to cause the issue : "ERROR in ./node_modules/simple-git/src/index.js Module not found: Error: Can't resolve 'child_process' in 'C:\Users\Martin\Documents\Cours\Projet\Githarpon\git-harpon\node_modules\simple-git\src' resolve 'child_process' in 'C:\Users\Martin\Documents\Cours\Projet\Githarpon\git-harpon\n

Initialising objects with functions in TypeScript

Lets say I have a class A like this: export class A extends Observable { constructor( public id: string ) { super(); } public testCallFunction() { return "Function called on object with id " + this.id; } } I can initialise an array of A like this and the function is exposed: this.data = [new A("1"), new A("2")]; When I initialise the array like this, it does not let me call the function due to "type error": this.data = [{ "id": "1" }, { "id": "2" }] as Ar

Typescript Infer Parameter Type of a Function

I would like to infer the type of a parameter in Typescript but was not lucky until yet. I have the following Code // is it possible to find out the type of the payload parameter? type Dispatch<T> = (prop: keyof T, payload?: any) => any; class TestClass<T> { obj: T; dispatch: Dispatch<T> = (prop, payload) => { const func = this.obj[prop]; return (func as any)(payload); }; constructor(obj: T) { this.obj = obj; } } interface SomeFuncs { foo(pay

Typescript Extending discriminated union of plain objects defined in library package in code using that read-only lib

I have a library that writes plain JS objects to storage. Those objects all have types. I use a discriminated union with a common "type" property. The problem is that code that uses that library (then under node_modules/) cannot update the union. I just switched the project from Flow to TypeScript. In Flow I "solved" it by providing a global type in flow-typed/. I had an empty global type within the library code's flow-typed/ directory, but that is overwritten (the whole file ignored, actually

Force idea to use nice typescript imports from node_modules

Now when importing something from node_modules I get something like: import {OnInit} from '../../../node_modules/@angular/core/src/metadata/lifecycle_hooks'; or (If i change settings) import {OnInit} from 'node_modules/@angular/core/src/metadata/lifecycle_hooks'; And what I want is obvious '@angular/core'; (After import I can modify import to nice version and it works. So I think this is related to some Idea settings/folder excusion/...)

Typescript Within the context of NGRX selectors how to create a selector that will return a set of objects where you have given a list of id(s) for those objects

The way ngrx goes about returning a set from a passed array out of the stored state, seems wrong. I'm using ngrx-entities so, as you all know an entity is actually stored as an associative array with some sort of key and an object. I have written selectors that look like this: export const selectSanctuariesState = createFeatureSelector<fromSanctuary.SanctuariesState>('sanctuaries'); export const selectSanctuaryById = (id: string) => createSelector( selectSanctuariesState, s

Typescript setInterval function not working in RxJs 6 +

I am learning RxJs. I've created an Observable that emits some values and for one value I tried putting a SetInterval(). But it is not emitting the values during that interval. Is there any alternative function or Am I missing anything else. Below is the code: import { Observable } from 'rxjs/Observable'; import { from,interval } from 'rxjs' var observable = Observable.create(function subscribe(observer : any){ try{ observer.next('Hey guys!') observer.next('How are yu ??') setIn

Typescript Can I use a generic type as a key name in an object?

I have a function that I want to return as an interface, where the generic parameters of that function dictate the key name & value type. I want to prevent (or at least minimize) the amount of repetition in the calling code, or "DRY". Every attempt to use the generic type as an object key results in an error like "K only refers to a type, but is being used as a value here.", which is understandable since that's just how typescript works. But I want to do this anyway :) This is what I've g

Typescript Promise<MyClass | undefined> not returning optional variable

I have a function basically like this function foo(): Promise<MyClass | undefined> { if(somethingGoesWrong) { return Promise.resolve(undefined); } return Promise.resolve(new MyClass()); } Outside the function, I call this const x = await foo() The problem is my IDE which is VSCode won't treat x as MyClass | undefined. It will just be MyClass. I don't know is this an IDE problem or there are rules such as "Promise can't resolve undefined". I know a better way to

Typescript Partial<> on specific key

I have a typescript interface describing mongodb database data like : interface Foo { _id: string, name: string, fish: { _id: string, name: string, }, } I have a method that is building one data to insert in the database, like : function pushNewFish() { const obj: Foo = { name: 'obiwan', fish: { name: 'kenobi', }, }; // ... } The problem is : I do not implements every _id elements that are specific to database. I have the possibility

Typescript make param optional

Here is playground I am trying to make a parameter optional, but still make typescript understand what will get returned from function. If param is defined, then type of param is returned. Otherwise - if no param is provided, function will return undefined. const meh = <T>(initialData?: T): { data: T | undefined} => { if (initialData) { return { data: initialData } } return { data: undefined } } const res1: undefined = meh().data // is ok: type Res

Typescript Can a decorator change a method's signature?

Consider a function: function handleFoo(foo: number){ // ... } I'd like to have a decorator which resolves foo, like: @fetchFromApi('/foo') function handleFoo(foo: number){ // ... } where @fetchFromApi calls my API and then calls handleFoo with the result - at this point I would wish to call handleFoo without parameters, because foo is going to be fetchedFromApi. However, TypeScript's type checker still expects me to call handleFoo with a single argument. Is it possible to change

TypeScript: Get Generic function type from "typeof" generic function

I'm pretty sure TypeScript has a way of doing this but I haven't figured it out yet. Is there a way to extract a generic type from the typeof a generic function? Consider this simple generic function: function echo<T> (input: T) { return input; } I want to extract the generic type of this function. I tried: type IEchoFn = typeof echo; But it's unusable: const echo2: IEchoFn = (input: string) => input; ^^^^^ // Type '(input: string) => string' is not // assigna

typescript @types/yup validate return undefined?

I have been using yup for my typescript project for a while. It requires @types/yup for the type definitions. I was using v0.26.4 of it, and it was all good. But today I update the dependency to v0.29.3. Something is wrong here: //The object schema constructor from <T extends object>(fields?: ObjectSchemaDefinition<T>): ObjectSchema<T>; //changed to <T extends object>(fields?: ObjectSchemaDefinition<T>): ObjectSchema<T | undefined>; //then for my validati

Typescript Does assigning an object value before spreading it change its type?

When constructing an object by assigning some properties and spreading the rest from another object, it seems that the type of the spread object varies depending on whether it is first assigned to an intermediatry variable. For example, here you'll find a sample sandbox where the following works just fine, const render = (): RenderReturn => { const div = document.createElement("div"); const obj = getQueriesForElement(div); return { someProp: "foo", ...obj

TypeScript infering the type while looping over a map

The particular TypeScript code receives from the back-end an array of Config type objects. And for each Config object in the array, it needs to update / populate the params with the appropriate information, and after that do a set of calls, with the populated params. I am having trouble with creating the appropriate types for this scenario. Here is some code of the current state of the system, and the problem I encounter. There is an enum with all the available partners: enum TheEnum { Foo

Typescript Module '"@react-native-firebase/firestore"' has no exported member 'CollectionReference'. ts(2614)

I use TypeScript and React native with Firestore (no expo). On the import: import { CollectionReference } from '@react-native-firebase/firestore' I get the error message: Module '"@react-native-firebase/firestore"' has no exported member 'CollectionReference'. Did you mean to use 'import CollectionReference from "@react-native-firebase/firestore"' instead?ts(2614) I installed the module, trying both yarn and npm install. Here is the packages.json points of interest: { &

Typescript Generic call signatures and type inference

I have the following two snippets: 1. interface Identity { <T extends any>(arg: T): T } function identity<T>(arg: T) { return arg } let id: Identity = identity id() // the argument here is of type unknown interface Identity<E> { <T extends E>(arg: T): T } function identity<T>(arg: T) { return arg } let id: Identity<any> = identity id() // the argument here is of type any In the first case I have a named ObjectType with a generic call

Typescript Where do I get the "types" for certain modules in "firebase"?

This is more of a broad question I'm using Firebase as an example for. In my react project, I might want to import firebase from "@firebase/app" which makes sense. But lets say I want this const locationRef to be typed as a firebase ref type. From what do I import "ref" from? Where are these types generally located for any general typescript library?

Typescript Typing reducer payload as an object type or array of such

I'm using useReducer to maintain state for an array of object types and I have a few action types. The interfaces looks like: interface MyObject { id: string; foo: string; bar: string; } interface Action { type: 'add' | 'remove' | 'update'; payload?: Partial<MyObject>; } The reducer function: const reducer = (current: MyObject[], action: Action): MyObject[] => { switch (action.type) { case 'add': return [...current, createBaseMyObject()]; case 'remove':

Typescript How to apply tsconfig.json configuration to all subfolders of a project

I have made project folder recently and I'm trying to solve some problems and algorithms with typescript. This is folder structure of my project below. Each folder's contains an index.ts file which have all logic of the problem goes there. This is my attempt to use an ES6 feature in algo3/index.ts `*`.repeat(picture[0].length + 2); but I have faced this error **Property 'repeat' does not exist on type '"*"'. Do you need to change your target library? Try changing the `lib` compiler o

Typescript How to type some fields of an object in typecsript

Is it possible to strongly type only a subset of an object? I tried doing this: const foo = { // many properties here which are inferred (primitives) nested: {} as {} | { bar: string } } // simulating something that might happen if (Math.random() > 0.5) { foo.nested.bar = 'bar' // Getting the following error // Property 'bar' does not exist on type '{} | { bar: string; }'. // Property 'bar' does not exi st on type '{}'. } // Getting the same error // Property 'bar' does not exi

Typescript How to declare DOM as possibly undefined

My colleagues and I are currently building a new Vue SSR app using Nuxt inside a monorepo. We have the Nuxt app as a package and another one being our component library. We're all quite new in Typescript, but we were able to set everything up without any issue. The problem is: the component library should be SSR friendly, but shouldn't be aware of Nuxt itself so I would rather use if (typeof window !== 'undefined') than if (process.browser) when accessing window properties. Now I'm wondering if

Next.js project deployment was failed by typescript types

I'm trying to deploy my project by vercel. i wrote it with next.js and typescript. i'm using Next-auth with credentials provider for authentication. by default this package for authentication has an object for session something like this: { name?: string; email?: string; image?: string; }. here's the point: i added an id property to this object as string in the types file of this package, i just want to use the user id in the session. everythis works fine and i can use the id for the backend and

  1    2   3   4   5   6  ... 下一页 最后一页 共 148 页