Coder Social home page Coder Social logo

microsoft / typescript-react-native-starter Goto Github PK

View Code? Open in Web Editor NEW
1.9K 1.9K 213.0 249 KB

A starter template for TypeScript and React Native with a detailed README describing how to use the two together.

License: MIT License

Java 12.36% JavaScript 2.62% Objective-C 38.44% TypeScript 31.47% Starlark 15.10%

typescript-react-native-starter's Introduction

TypeScript React Native Starter

Prerequisites

Because you might be developing on one of several different platforms, targeting several different types of devices, basic setup can be involved. You should first ensure that you can run a plain React Native app without TypeScript. Follow the instructions on the React Native website to get started. When you've managed to deploy to a device or emulator, you'll be ready to start a TypeScript React Native app.

You will also need Node.js, NPM, and Yarn.

Initializing

Once you've tried scaffolding out an ordinary React Native project, you'll be ready to start adding TypeScript. Let's go ahead and do that.

react-native init MyAwesomeProject
cd MyAwesomeProject

Adding TypeScript

The next step is to add TypeScript to your project. The following commands will:

  • add TypeScript to your project
  • add React Native TypeScript Transformer to your project
  • initialize an empty TypeScript config file, which we'll configure next
  • add an empty React Native TypeScript Transformer config file, which we'll configure next
  • Adds typings for React and React Native

Okay let's go ahead and run these.

yarn add --dev typescript
yarn add --dev react-native-typescript-transformer
yarn tsc --init --pretty --jsx react-native
touch rn-cli.config.js
yarn add --dev @types/react @types/react-native

The tsconfig.json file contains all the settings for the TypeScript compile. The defaults created by the command above are mostly fine, but open the file and uncomment the following line:

{
  ...
  // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
  ...
}

The rn-cli.config.js contains the settings for the React Native TypeScript Transformer. Open it and add the following:

module.exports = {
  getTransformModulePath() {
    return require.resolve("react-native-typescript-transformer");
  },
  getSourceExts() {
    return ["ts", "tsx"];
  }
};

Migrating to TypeScript

Rename the generated App.js and __tests__/App.js files to App.tsx. index.js needs to use the .js extension. All new files should use the .tsx extension (or .ts if the file doesn't contain any JSX).

If you try to run the app now, you'll get an error like object prototype may only be an object or null. This is caused by a failure to import the default export from React as well as a named export on the same line. Open App.tsx and modify the import at the top of the file:

-import React, { Component } from 'react'
+import React from 'react'
+import { Component } from 'react'

Some of this has to do with differences in how Babel and TypeScript interoperate with CommonJS modules. In the future, the two will stabilize on the same behavior.

At this point, you should be able to run the React Native app.

Adding TypeScript Testing Infrastructure

Since we're using Jest, we'll want to add ts-jest to our devDependencies.

yarn add --dev ts-jest

Then, we'll open up our package.json and replace the jest field with the following:

"jest": {
  "preset": "react-native",
  "moduleFileExtensions": [
    "ts",
    "tsx",
    "js"
  ],
  "transform": {
    "^.+\\.(js)$": "<rootDir>/node_modules/babel-jest",
    "\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
  },
  "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
  "testPathIgnorePatterns": [
    "\\.snap$",
    "<rootDir>/node_modules/"
  ],
  "cacheDirectory": ".jest/cache"
}

This will configure Jest to run .ts and .tsx files with ts-jest.

Installing Type Declaration Dependencies

To get the best experience in TypeScript, we want the type-checker to understand the shape and API of our dependencies. Some libraries will publish their packages with .d.ts files (also called "typed declaration" or "type definition" files) which can describe the shape of the underlying JavaScript. For other libraries, we'll need to explicitly install the appropriate package in the @types/ npm scope.

For example, here we'll need types for Jest, React, and React Native, and React Test Renderer.

yarn add --dev @types/jest @types/react @types/react-native @types/react-test-renderer

We saved these declaration file packages to our dev dependencies because we're not publishing this package as a library to npm. If we were, we might have to add some of them as regular dependencies.

You can read more here about getting .d.ts files.

Ignoring More Files

For your source control, you'll want to start ignoring the .jest folder. If you're using git, we can just add entries to our .gitignore file.

# Jest
#
.jest/

As a checkpoint, consider committing your files into version control.

git init
git add .gitignore # import to do this first, to ignore our files
git add .
git commit -am "Initial commit."

Adding a Component

We can now add a component to our app. Let's go ahead and create a Hello.tsx component. Create a components directory and add the following example.

// components/Hello.tsx
import React from "react"
import { Button, StyleSheet, Text, View } from "react-native"

export interface Props {
  name: string
  enthusiasmLevel?: number
  onIncrement?: () => void
  onDecrement?: () => void
}

interface State {
  enthusiasmLevel: number
}

export class Hello extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props)

    if ((props.enthusiasmLevel || 0) <= 0) {
      throw new Error("You could be a little more enthusiastic. :D")
    }

    this.state = {
      enthusiasmLevel: props.enthusiasmLevel || 1
    }
  }

  onIncrement = () => this.setState({ enthusiasmLevel: this.state.enthusiasmLevel + 1 });
  onDecrement = () => this.setState({ enthusiasmLevel: Math.max(0, this.state.enthusiasmLevel - 1) });
  getExclamationMarks = (numChars: number) => Array(numChars + 1).join("!")

  render() {
    return (
      <View style={styles.root}>
        <Text style={styles.greeting}>
          Hello {this.props.name + this.getExclamationMarks(this.state.enthusiasmLevel)}
        </Text>

        <View style={styles.buttons}>
          <View style={styles.button}>
            <Button
              title="-"
              onPress={this.onDecrement}
              accessibilityLabel="decrement"
              color="red"
            />
          </View>

          <View style={styles.button}>
            <Button
              title="+"
              onPress={this.onIncrement}
              accessibilityLabel="increment"
              color="blue"
            />
          </View>
        </View>
      </View>
    )
  }
}

// styles

const styles = StyleSheet.create({
  root: {
    alignItems: "center",
    alignSelf: "center"
  },
  buttons: {
    flexDirection: "row",
    minHeight: 70,
    alignItems: "stretch",
    alignSelf: "center",
    borderWidth: 5
  },
  button: {
    flex: 1,
    paddingVertical: 0
  },
  greeting: {
    color: "#999",
    fontWeight: "bold"
  }
})

Whoa! That's a lot, but let's break it down:

  • Instead of rendering HTML elements like div, span, h1, etc., we're rendering components like View and Button. These are native components that work across different platforms.
  • Styling is specified using the StyleSheet.create function that React Native gives us. React's StyleSheets allow us to control our layout using Flexbox, and style using other constructs similar to those in CSS stylesheets.

Adding a Component Test

Now that we've got a component, let's try testing it.

We already have Jest installed as a test runner. We're going to write snapshot tests for our components, let's add the required add-on for snapshot tests:

yarn add --dev react-addons-test-utils

Now let's create a __tests__ folder in the components directory and add a test for Hello.tsx:

// components/__tests__/Hello.tsx
import React from 'react'
import renderer from 'react-test-renderer'

import { Hello } from "../Hello"

it("renders correctly with defaults", () => {
  const button = renderer.create(<Hello name="World" enthusiasmLevel={1} />).toJSON()
  expect(button).toMatchSnapshot()
})

The first time the test is run, it will create a snapshot of the rendered component and store it in the components/__tests__/__snapshots__/Hello.tsx.snap file. When you modify your component, you'll need to update the snapshots and review the update for inadvertent changes. You can read more about testing React Native components here.

Next Steps

Check out our React TypeScript tutorial where we also cover topics like state management with Redux. These same subjects can be applied when writing React Native apps.

Additionally, you may want to look at the ReactXP if you're looking for a component library written entirely in TypeScript that supports both React on the web as well as React Native.

Helpful Resources

typescript-react-native-starter's People

Contributors

ashfurrow avatar danielrosenwasser avatar dependabot[bot] avatar dmitriyshx avatar henrikra avatar jablko avatar mhegazy avatar microsoftopensource avatar msftgits avatar niklassaers avatar sandersn avatar soroushchehresa avatar yedidyak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

typescript-react-native-starter's Issues

why i need RegisteredStyle type?

Error:(26, 11) TS2322: Type 'RegisteredStyle<{ fontSize: number; textAlign: string; margin: number; }>' is not assignable to type 'StyleProp<TextStyle>'. Type 'RegisteredStyle<{ fontSize: number; textAlign: string; margin: number; }>' is not assignable to type 'RecursiveArray<false | TextStyle | RegisteredStyle<TextStyle> | null | undefined>'. Property 'length' is missing in type 'Number & { __registeredStyleBrand: { fontSize: number; textAlign: string; margin: number; }; }'.
You did not declare the type of the style file when creating the style in hello.tsx in your readme file,
Why did I have this error when I created my own style

Android Licences with Javascript Accepted and with Typescript not

Hello together,
if I try to create an React Native Project with Typescript it tells me anytime that I have not yet accepted the Licences of Android, but I did it already and with Javascript it works fine. I used this Project for test it

* What went wrong:
A problem occurred configuring project ':app'.
> You have not accepted the license agreements of the following SDK components:
[Android SDK Platform 23, Android SDK Build-Tools 23.0.1].
Before building your project, you need to accept the license agreements and complete the installation of the missing components using the Android Studio SDK Manager.
Alternatively, to learn how to transfer the license agreements from one workstation to another, go to http://d.android.com/r/studio-ui/export-licenses.html

Licences:
sdkmanager.bat --licenses                                           
Warning: File C:\Users\subso\.android\repositories.cfg could not be loaded.                                             
All SDK package licenses accepted.======] 100% Computing updates...  

Maybe anyone of you can help me, thanks alot

Greetings
Justin

React Native 0.56

Currently, there some issues with running TypeScript + React Native 0.56 + Jest. Would it be possible to get some official guides on how to run the newest versions of TS, RN and Jest?

Command `run-ios` unrecognized after adding typescript modules

Follow the guide, I get the below package.json:

{
  "name": "one",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "16.2.0",
    "react-native": "0.52.0"
  },
  "devDependencies": {
    "@types/enzyme": "^3.1.6",
    "@types/jest": "^22.0.1",
    "@types/react": "^16.0.34",
    "@types/react-native": "^0.51.9",
    "@types/react-test-renderer": "^16.0.0",
    "babel-jest": "22.0.4",
    "babel-preset-react-native": "4.0.0",
    "enzyme": "^3.3.0",
    "jest": "22.0.5",
    "react-addons-test-utils": "^15.6.2",
    "react-dom": "^16.2.0",
    "react-test-renderer": "16.2.0",
    "ts-jest": "^22.0.1",
    "typescript": "^2.6.2"
  },
  "jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ],
    "transform": {
      "^.+\\.(js)$": "<rootDir>/node_modules/babel-jest",
      "\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
    "testPathIgnorePatterns": [
      "\\.snap$",
      "<rootDir>/node_modules/",
      "<rootDir>/lib/"
    ],
    "cacheDirectory": ".jest/cache"
  }
}
react-native -v

react-native-cli: 2.0.1
react-native: n/a - not inside a React Native project directory

When I run this command line:

npm install --save-dev @types/jest @types/react @types/react-native @types/react-test-renderer

Then I run

react-native run-ios

got the tips:


Command `run-ios` unrecognized. Make sure that you have run `npm install` and that you are inside a react-native project.

How should I do for it? Everybody can give me some suggestions, Thank you in advance!

Add debug config

I think it would be good to put in this repo vscode config and instruction for debugging. Looks like it is not so trivial if you have TypeScript environment.

unmet dependencies when running `npm i`

I cloned the repo and ran npm i:

➜  TypeScript-React-Native-Starter git:(master) ✗ npm i
npm ERR! Darwin 16.7.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "i"
npm ERR! node v4.5.0
npm ERR! npm  v2.15.9
npm ERR! code EPEERINVALID

npm ERR! peerinvalid The package [email protected] does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants [email protected]
npm ERR! peerinvalid Peer [email protected] wants react@^15.6.2
npm ERR! peerinvalid Peer [email protected] wants react@^15.6.2
npm ERR! peerinvalid Peer [email protected] wants [email protected] || 0.14.x || ^15.0.0-0 || 15.x

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/martins/TypeScript-React-Native-Starter/npm-debug.log

How do we fix this?

Example project not compiling properly

Steps to reproduce

$ git clone https://github.com/Microsoft/TypeScript-React-Native-Starter
$ git checkout 3fc367a1ab877316ed2dd3001e113ddc2080930e
$ yarn install
$ tsc -p tsconfig.json --outDir build

Result

node_modules/@types/react-native/index.d.ts(3415,42): error TS2304: Cannot find name 'Map'.
node_modules/@types/react-native/index.d.ts(3428,42): error TS2304: Cannot find name 'Map'.
node_modules/@types/react-native/index.d.ts(8685,18): error TS2717: Subsequent property declarations must have the same type.  Property 'geolocation' must be of type 'Geolocation', but here has type 'GeolocationStatic'.

Expected Result

To compile properly.

Add support for create-react-native-app instead?

Are you guys considering supporting create-react-native-app? I don't think most new developers finding create-react-native will use the react clip anymore? Would really love "official" support from MS.

Example test for Hello.tsx does not work

I'm following the guide from https://github.com/Microsoft/TypeScript-React-Native-Starter#adding-a-component but when I run npm test I get this error:

 FAIL  src/components/__tests__/Hello.tsx
   Test suite failed to run

    xx/src/components/__tests__/Hello.tsx: Unexpected token (9:35)
         7 | const Hello_1 = require("../Hello");
         8 | it('renders correctly with defaults', () => {
      >  9 |     const hello = enzyme_1.shallow(<Hello_1.default name="World"/>);
           |                                    ^
        10 |     expect(hello.find(react_native_1.Text).render().text()).toEqual("Hello World!");
        11 | });

Any idea what's wrong?
My packages.json

Use of allowSyntheticDefaultImports flag in tsconfig.json

Reading README.md it says:

Moving files over to TypeScript

[...]

We'll immediately get a few errors, but they're easy enough to fix. The changes will include:

Replace import React, {Component} from 'react'; with import * as React from 'react';

I am using React+Typescript, and activating the flag allowSyntheticDefaultsImports in tsconfig.json solves this issue. Now you can use import React, {Component} from 'react' without modificate the code.

I was wondering if it is worth I send a pull request to modify README.md. Thanks

breakpoints in tests don't work in VSCode

Using VSCode to debug tests. Setting breakpoints in the test-files doesn't work, and just gets ignored. Interestingly, inserting debugger; into the tests works fine.

This is my launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Debug Jest",
            "program": "${workspaceRoot}/node_modules/jest/bin/jest.js",
            "args": ["--runInBand", "--no-cache"],
            "cwd": "${workspaceRoot}",
            "console": "integratedTerminal",
            "sourceMaps": true,
            "smartStep": true
        }
    ]
}

Update to use modern techniques for React Native + TS

From listening to native devs moving to TS, this repo is often used as the reference for RN + TS, and I think it's time we gave it a spring clean.

This issue is more of a TODO list to bring this up to speed:

ReactXP project update?

Please update ReactXP seed with latest libraries of react-native and react along with their dependencies

react-native run-ios not working

my project is git clone https://github.com/tassdr/react-native-template.git

downloaded there and trying to run in my macOS but error remains like this

Admins-MacBook-Pro:react-native-template admin$ react-native run-ios
error iOS project folder not found. Are you sure this is a React Native project?. Run CLI with --verbose flag for more details.
Admins-MacBook-Pro:react-native-template admin$

please help me

Path Aliasing?

the generated code doesn't fully resolve paths specified in the tsconfig.json

Translated READMEs (meta-issue)

In #35 (comment), @phwb asked about providing a translated README.md in Russian.

We're welcoming translations and any help with reviewing those translations to help users from around the world learn more easily. If you'd like to help provide translations, let us know here!

State of this project?

Is it still being maintained?

Currently there's a lot of issues and pull requests with only automated replies or replies by other users. Latest commits are mostly 9 months ago.

Also, the readme still mentions android/ios.js, which have been deprecated(and this is fixed with this PR.)

no code hint to use StyleSheet.create

There is no code hint to use this method(use webstrom ide)

const styles = StyleSheet.create({
root: {
alignItems: "center",
alignSelf: "center"
}
});

hope when write 'a', a code prompt appears. [alignSelf....all start with 'a' ]

NPM 5+?

I may be wrong but I don't think NPM 5 is out yet 😄
Maybe meant to be Node 5+?

Before you do this, it might help to have Yarn or npm 5+ installed

I can issue a pull request tomorrow to fix this

Unable to resolve "../../App" from "node_modules/expo/AppEntry.js"

I have renamed the top level App.js to App.tsx but when running simulator, js bundle failed to build because of the following error.
Unable to resolve "../../App" from "node_modules/expo/AppEntry.js".

dependencies:
"@expo/samples": "2.1.1", "expo": "^30.0.1", "react": "16.3.1", "react-native": "https://github.com/expo/react-native/archive/sdk-30.0.0.tar.gz", "react-navigation": "^2.16.0", "ts-jest": "^23.10.1"

Thanks!

Hello.tsx does not compile via MSBUILD using TypeScript 2.2 or 2.3

Compiling Hello.tsx, or any other React Native TypeScript code, I get the same JSX errors below despite using React in the csproj options. I have copy and pasted the csproj options I am using as well. Known? Thanks.

Severity	Code	Description	Project	File	Line	Suppression State
Error	TS2604	JSX element type 'View' does not have any construct or call signatures.	ReactTestApp, TestApp.React (tsconfig project)	C:\Users\nmyhre\Source\Repos\TestApp.React\windows\ReactTestApp\TypeScriptSrc\Hello.tsx	21	Active
Error	TS2604	JSX element type 'Text' does not have any construct or call signatures.	ReactTestApp, TestApp.React (tsconfig project)	C:\Users\nmyhre\Source\Repos\TestApp.React\windows\ReactTestApp\TypeScriptSrc\Hello.tsx	22	Active
Error	TS2604	JSX element type 'View' does not have any construct or call signatures.	ReactTestApp, TestApp.React (tsconfig project)	C:\Users\nmyhre\Source\Repos\TestApp.React\windows\ReactTestApp\TypeScriptSrc\Hello.tsx	25	Active
Error	TS2604	JSX element type 'View' does not have any construct or call signatures.	ReactTestApp, TestApp.React (tsconfig project)	C:\Users\nmyhre\Source\Repos\TestApp.React\windows\ReactTestApp\TypeScriptSrc\Hello.tsx	26	Active
Error	TS2604	JSX element type 'Button' does not have any construct or call signatures.	ReactTestApp, TestApp.React (tsconfig project)	C:\Users\nmyhre\Source\Repos\TestApp.React\windows\ReactTestApp\TypeScriptSrc\Hello.tsx	27	Active
Error	TS2604	JSX element type 'View' does not have any construct or call signatures.	ReactTestApp, TestApp.React (tsconfig project)	C:\Users\nmyhre\Source\Repos\TestApp.React\windows\ReactTestApp\TypeScriptSrc\Hello.tsx	29	Active
Error	TS2604	JSX element type 'Button' does not have any construct or call signatures.	ReactTestApp, TestApp.React (tsconfig project)	C:\Users\nmyhre\Source\Repos\TestApp.React\windows\ReactTestApp\TypeScriptSrc\Hello.tsx	30	Active
Error	TS17004	Cannot use JSX unless the '--jsx' flag is provided.	TestApp.React (tsconfig project)	C:\Users\nmyhre\Source\Repos\TestApp.React\windows\ReactTestApp\TypeScriptSrc\Hello.tsx	21	Active
Error	TS17004	Cannot use JSX unless the '--jsx' flag is provided.	TestApp.React (tsconfig project)	C:\Users\nmyhre\Source\Repos\TestApp.React\windows\ReactTestApp\TypeScriptSrc\Hello.tsx	22	Active
Error	TS17004	Cannot use JSX unless the '--jsx' flag is provided.	TestApp.React (tsconfig project)	C:\Users\nmyhre\Source\Repos\TestApp.React\windows\ReactTestApp\TypeScriptSrc\Hello.tsx	25	Active
Error	TS17004	Cannot use JSX unless the '--jsx' flag is provided.	TestApp.React (tsconfig project)	C:\Users\nmyhre\Source\Repos\TestApp.React\windows\ReactTestApp\TypeScriptSrc\Hello.tsx	26	Active
Error	TS17004	Cannot use JSX unless the '--jsx' flag is provided.	TestApp.React (tsconfig project)	C:\Users\nmyhre\Source\Repos\TestApp.React\windows\ReactTestApp\TypeScriptSrc\Hello.tsx	27	Active
Error	TS17004	Cannot use JSX unless the '--jsx' flag is provided.	TestApp.React (tsconfig project)	C:\Users\nmyhre\Source\Repos\TestApp.React\windows\ReactTestApp\TypeScriptSrc\Hello.tsx	29	Active
Error	TS17004	Cannot use JSX unless the '--jsx' flag is provided.	TestApp.React (tsconfig project)	C:\Users\nmyhre\Source\Repos\TestApp.React\windows\ReactTestApp\TypeScriptSrc\Hello.tsx	30	Active

  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
    <TypeScriptCompileOnSaveEnabled>True</TypeScriptCompileOnSaveEnabled>
    <TypeScriptTarget>ES6</TypeScriptTarget>
    <TypeScriptJSXEmit>React</TypeScriptJSXEmit>
    <TypeScriptNoImplicitAny>True</TypeScriptNoImplicitAny>
    <TypeScriptModuleKind>ES6</TypeScriptModuleKind>
    <TypeScriptRemoveComments>False</TypeScriptRemoveComments>
    <TypeScriptOutFile />
    <TypeScriptOutDir>C:\Users\nmyhre\Source\Repos\TestApp.React\build</TypeScriptOutDir>
    <TypeScriptGeneratesDeclarations>False</TypeScriptGeneratesDeclarations>
    <TypeScriptNoEmitOnError>False</TypeScriptNoEmitOnError>
    <TypeScriptSourceMap>True</TypeScriptSourceMap>
    <TypeScriptMapRoot />
    <TypeScriptSourceRoot />
    <TypeScriptAllowSyntheticDefaultImports>True</TypeScriptAllowSyntheticDefaultImports>
    <TypeScriptAlwaysStrict>True</TypeScriptAlwaysStrict>
  </PropertyGroup>

Add support to Storybook

I think that today adding Storybook to RN code is essential.
I would like to see that as part of the bundle.

Using functions within StyleSheet

Hey guys,

Often times I want to do something like

const styles = StyleSheet.create({
  square: (size: number) => ({
    width: size,
    height: size,
  }),
})

Now this doesn't work, because I get Type '(size: number) => { width: number; height: number; }' is not assignable to type 'ViewStyle | TextStyle | ImageStyle'. I've tried doing things like

interface Style {
  square: (width: number) => ViewStyle
}

const styles = StyleSheet.create<Style>({
  square: (size: number) => ({
    width: size,
    height: size,
  }),
})

But then I get Type 'Style' does not satisfy the constraint 'NamedStyles<any> | NamedStyles<Style>'.

Any ideas how to deal with this?

Example test for Hello.tsx does not work (Microsoft/TypeScript-React-Native-Starter) Ask Question

I' following the guide from https://github.com/Microsoft/TypeScript-React-Native-Starter#adding-a-component but when I run npm test I get this error:

 FAIL  src/components/__tests__/Hello.tsx
   Test suite failed to run

    xx/src/components/__tests__/Hello.tsx: Unexpected token (9:35)
         7 | const Hello_1 = require("../Hello");
         8 | it('renders correctly with defaults', () => {
      >  9 |     const hello = enzyme_1.shallow(<Hello_1.default name="World"/>);
           |                                    ^
        10 |     expect(hello.find(react_native_1.Text).render().text()).toEqual("Hello World!");
        11 | });

Any idea what's wrong?
My packages.json

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.