[Typescript] satisfies - value‐level check:

You’re seeing that

const scores = {} satisfies Record<string,number>

does check at compile-time “hey, {} can be a Record<string,number>”, but it doesn’t become that type—scores is still inferred as {}. So when you do

scores.english = 100

TS still thinks scores has no properties.

By contrast:

const scores: Record<string,number> = {}
scores.english = 100 // ✅
here you’ve widened the variable’s type itself, so you get the indexable shape.
 

Key idea

  • satisfies is a value‐level check: it ensures the RHS value is compatible with the given type, but it doesn’t change the declared type of the variable.

  • An explicit : Record<string,number> is a variable‐level annotation: it tells TS “treat this var as that type,” so you can do scores.anyKey = ….

Use satisfies when you want to preserve narrow literal types on the value but still get a compile-time check, not when you need the var itself to be that wider type.

 
posted @ 2025-06-23 02:31  Zhentiw  阅读(5)  评论(0)    收藏  举报