Skip to content

Suggestion: Infer literal types for getter only properties that return literals #11467

Closed
@aluanhaddad

Description

@aluanhaddad

Suggestion: Infer literal types for getter only properties that return literals.

This suggestion arose from reading #11465 the example below comes directly from that issue.

TypeScript Version: nightly (2.0.0-dev.20161008)

Code

// A *self-contained* demonstration of the problem follows...
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     
    }
});

I tried a different workaround than the ones presented by @jovdb in #11465

const styles = StyleSheet.create({
  text: {
      get position() { return 'absolute'; },
      top: 0,
      left: 0
    }
});

Expected behavior:
The type of text.position is inferred as 'absolute'
Actual behavior:
The type of text.position is inferred as string

My reasoning here is that while the following rules, outlined in #10676, make complete sense in general, they are not ideal for getter only properties

  • In a function with no return type annotation, if the inferred return type is a literal type (but not a literal union type) and the function does not have a contextual type with a return type that includes literal types, the return type is widened to its widened literal type.
  • The type inferred for a property in an object literal is the widened literal type of the expression unless the property has a contextual type that includes literal types.

I am not sure if both of these rules apply here or only the second.

Metadata

Metadata

Assignees

No one assigned

    Labels

    SuggestionAn idea for TypeScriptWorking as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions