Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TS2322: Type 'string' is not assignable to type '"absolute" | "relative" | undefined' #11465

Closed
jovdb opened this issue Oct 8, 2016 · 3 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@jovdb
Copy link

jovdb commented Oct 8, 2016

TypeScript Version: 2.1.0-dev.20161008

Minimal ReactNative Component to illustrate the problem:

import React, { Component } from 'react';
import { StyleSheet, Text } from 'react-native';

export class Sample extends Component<{}, {}> {
    render() {
        return (
            <Text style={styles.text}>Hello TypeScript</Text> // error on styles, see below
        );
    }
}

const styles = StyleSheet.create({
    text: {
        position: 'absolute', // cause of the error: string instead of 'absolute'
        top: 0,
        left: 0     
    }
});

Error:

error TS2322: Type '{ position: string; top: number; left: number; }' is not assignable to type 'TextStyle | undefined'.
  Type '{ position: string; top: number; left: number; }' is not assignable to type 'TextStyle'.
    Types of property 'position' are incompatible.
      Type 'string' is not assignable to type '"absolute" | "relative" | undefined'.

I like it that the reactnative declaration doesn't use string, but only allows the set of possible strings.

Is there any way to let TypeScript infer this to type 'absolute'?
Maybe if I could mark this position field as readonly, it could infer to type 'absolute'.

Related to #10676?

@jovdb
Copy link
Author

jovdb commented Oct 8, 2016

I don't like casting and prevent it as much as possible, but here are workarounds:

const styles = StyleSheet.create({
    text: {
        position: 'absolute',
        top: 0,
        left: 0     
    } as React.TextStyle // cast to existing interface
});

When there is not interface is exported (here: TextStyle), we can cast only field:

const styles = StyleSheet.create({
    text: {
        position: 'absolute' as 'absolute', // cast string to type 'absolute'
        top: 0,
        left: 0     
    }
});

@WKenya
Copy link

WKenya commented Nov 28, 2017

This is related to #19966.

@matthias-ccri
Copy link

This can also be the case: #21618 (comment)

@microsoft microsoft locked and limited conversation to collaborators Jul 31, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

4 participants