obj [“ any”]的打字稿元素类型定义

时间:2019-03-20 02:14:21

标签: typescript

在javascript中,您可以执行类似的操作,

import React from 'react';
import { shallow } from 'enzyme';
import config from '../../config';
import AboutScreen from '../AboutScreen';
import { Constants, WebBrowser } from 'expo';
const { termsAndConditionsUrl, privacyPolicyUrl } = config;

jest.mock('expo', () => ({
  Constants: {
    manifest: {
      version: '0.0.1',
      releaseChannel: 'PROD',
    }
  },
}));

it('renders with releaseChannel and version', () => {
  const wrapper = shallow(<AboutScreen />);
  expect(wrapper).toMatchSnapshot();  // Success!
  expect(wrapper.contains('PROD')).toBe(true);  // Success!
  expect(wrapper.contains('0.0.1')).toBe(true);  // Success!
});

it('renders with default releaseChannel', () => {
  Constants.manifest = {
    version: '0.0.2'
  };  // change the manifest property of Constants
  const wrapper = shallow(<AboutScreen />);
  expect(wrapper).toMatchSnapshot();  // Success!
  expect(wrapper.contains('DEV')).toBe(true);  // Success!
  expect(wrapper.contains('0.0.2')).toBe(true);  // Success!
});

我想在打字稿中做同样的事情

        let otherVariable = "ww"
        let obj = {
            a:"aa",
            b:"bb",
        }
        obj.a = "aaa";
        obj["c"] = "cc";
        obj["x"] = "xx";
        obj["y"] = "yy";
        obj[otherVariable] = "ww";

代码可以编译并且可以正常工作,但是我收到此消息,

let otherVariable = "ww" let obj:{a:string, b:string} = { a:"aa", b:"bb", } obj.a = "aaa"; obj["c"] = "cc"; // alert message here obj["x"] = "xx"; // alert message here obj["y"] = "yy"; // alert message here obj[otherVariable] = "ww"; // alert message here

2 个答案:

答案 0 :(得分:3)

TypeScript是JavaScript的强类型超集。

您的object的类型为{a:string, b:string},这意味着obj仅接受ab属性。

为您的obj重新定义类型

let otherVariable = "ww";
let obj: { [key: string]: string } = {
  a: "aa",
  b: "bb",
};
obj.a = "aaa";
obj["c"] = "cc";
obj["x"] = "xx";
obj["y"] = "yy";
obj[otherVariable] = "ww";

答案 1 :(得分:0)

将类型定义扩展为:{ a: string, b: string, [key: string]: string}

这样,您将告诉Typescript,您的对象可能具有带有string类型键的其他键值对。