Home > Enterprise >  Can I give anonymous object a type in typescript?
Can I give anonymous object a type in typescript?

Time:08-05

I have the following code:

hello({
  name: "Michael"
} as x) // <-- Except missing id here, but it doesn't

type x = {
  id: string
  name: string
}

function hello(x: any) {
  console.log(x)
}

TS Playground

This code throws no error beside I'm saying as x. This is a type assertion so it won't give me an error. However I want to check for the type here. How can I do this? I'm not able to modify the hello function in my code.

CodePudding user response:

You could create a generic type checker function:

function typeCheck<T>(obj: T) { return obj; }

hello(typeCheck<x>({
  name: "Michael"
}));

type x = {
  id: string
  name: string
}

function hello(x: any) {
  console.log(x)
}

TS Playground

CodePudding user response:

You can create a wrapper function where you can put your type and ask developers to use your function instead of hello directly.

hello({
  name: "Michael"
} as x) // <-- Except missing id here, but it doesn't

type x = {
  id: string
  name: string
}

function hello(x: any) {
  console.log(x)
}


type x = {
  id: string
  name: string
}

function myHello(x: x) {
  return hello(x)
}

myHello({
  name: "Michael"
}) // Will show error

  • Related