skip to Main Content

I want to convert this PHP script to TypeScript (nodejs).

$fruits = [
    'APPLE'=> [
        'color'=>'red',
        'size'=>'small'
    ],
    'BANANA'=>[
        'color'=>'yellow',
        'size'=>'middle'
    ]
];

echo $fruits['APPLE']['color'];

type info = {
  color: string,
  size: string
}

const fruits['APPLE']: info = {color:'red',size:'small'}

I get an error.

2

Answers


  1. In TypeScript, you can define an object with a similar structure to your PHP array.

    type FruitInfo = {
      color: string;
      size: string;
    };
    
    const fruits: Record<string, FruitInfo> = {
      APPLE: {
        color: 'red',
        size: 'small',
      },
      BANANA: {
        color: 'yellow',
        size: 'middle',
      },
    };
    
    console.log(fruits['APPLE'].color);
    
    Login or Signup to reply.
    1. It is convention to capitalise the first letter of type for clarity and readability.
    type Info = {
      color: string,
      size: string
    }
    
    1. Not correct JS syntax.
    const fruits['APPLE']: info = {color:'red',size:'small'}
    
    const fruits = {
      APPLE: {
        color: 'red',
        size: 'small
      }
    }
    
    1. Assign a type directly or use a type alias.
    const fruits: { [key: string]: Info } = {
      'APPLE': { color: 'red', size: 'small' },
      'BANANA': { color: 'yellow', size: 'middle' }
    };
    
    type Fruits = {
     [key: string]: Info
    }
    
    const fruits: Fruits = {
      'APPLE': { color: 'red', size: 'small' },
      'BANANA': { color: 'yellow', size: 'middle' }
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search