Explicitly typing an object with TypeScript

后端 未结 2 1865
小鲜肉
小鲜肉 2020-12-20 02:37

I\'m working on converting my little library from JavaScript to TypeScript, and I have a function there

function create(declarations: Declarations) {
         


        
2条回答
  •  星月不相逢
    2020-12-20 03:34

    It seems this is not possible to do, in the TypeScript Deep Dive book there's a section on exactly this. Although you can declare a type you can't actually create an object with it in TS:

    // No error on this type declaration:
    type Declarations = {
        [key: string]: string;
    } & {
        onMember: number;
        onCollection: number;
    }
    
    // Error does appear here indicating type `number` is not assignable to type `string`.
    const declarations: Declarations = {
        onMember: 0,
        onCollection: 0,
        other: 'Is a string'
    }
    

    TypeScript Playground link.

提交回复
热议问题